Fix my random image positioning script so the images don't overlap

狂风中的少年 提交于 2019-12-13 08:58:47

问题


I made a script (here's a fiddle that builds upon my JS) for random positioning of <li> elements.

The elements overlap each other, though.

How can i modify my code so the items don't overlap anymore?

This is the script:

var images = [];

function init() {
    $('.friend-selection li > div').each(function(){
        var id = this.id;
        var img = $('#img_' + id);
        var randomTop = 500*Math.random(); //random top position
        var randomLeft = 500*Math.random(); //random left position

        $("#parent_" + id).css({ //apply the position to parent divs
            top : randomTop,
            left : randomLeft
        });
    });
};

init(); 

I have this html. A ul with li items:

<li id="parent_picture1">
    <div id="picture1">    
        <div class="glow"></div>
        <img src="static/img/voorbeeld/vrouw.jpg" width="111" height="166" id="img_picture1">
        <span class="name">Naam Achternaam</span>
    </div>      
</li>

回答1:


I'd need to know a bit more about the problem to decide how I'd do this, but here are some ideas that may work.

If the images all have the same size, you should be able to do something using modulus, e.g. randomTop = (500 * Math.random()) % picWidth.

Of course you'd need to keep track of which slots you've already used, so if the pictures array is going to be dense I'd probably add the slots to a random array and iterate through it.

        var slots = [];

        for (var y = 0; y < 5; y++)
        {
            for (var x = 0; x < 5; x++)
            {
                slots.push([x, y]);
            }
        }

        slots.sort(function () { return (0.5 - Math.random()); });

        $('.friend-selection li > div').each(function() { ... }

(Note that the random method I used isn't that great.)

If the pictures aren't of a fixed size, things get more complicated. I'd start by taking a look at jQuery Masonry for code, ideas or even a complete solution.




回答2:


You need to save the coordinates of each random position in an array.

For each <li>:

  • Get a random coordinate pair random_coordinates.
    • Check random_coordinates against each pair in positions_array:
      • does random_coordinates[0] + the width of your <li> overlap the positions_array[i][0] + the width of your <li> range anywhere?
        • If yes, start over.
      • does random_coordinates[1] + the height of your <li> overlap the positions_array[i][1] + the height of your <li> range anywhere?
        • If yes, start over.
    • If no collisions have been detected, push the random_coordinates pair on positions_array, apply the css, proceed with the next <li> item.


来源:https://stackoverflow.com/questions/7807830/fix-my-random-image-positioning-script-so-the-images-dont-overlap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!