Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - Generate random element position and prevent overlapping in JavaScript

I have a holder div on the page where I want to load small images in on random position as a collage with 10px padding on each.

How can I make sure that images never overlap each other or holder div? Is there a plugin or function that I could use?

My code so far:

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function(){
$("#my_canvas img").each(
function(intIndex) {

var l = Math.floor(Math.random() * $("#my_canvas").width());
var t = Math.floor(Math.random() * $("#my_canvas").height());

$(this).css("left", l);
$(this).css("top", t);

$(this).bind(
    "click",
        function() {
            alert("l=" + l + " t=" + t);
        }
    );

}

);

});

   <style type="text/css">
    #my_canvas
    {
        background: #eee;
        border: black 1px solid;
        width: 800px;
        height: 400px;
    }
    #my_canvas img
    {
        padding: 10px;
        position:absolute;
    }
</style>

<div id="my_canvas">
    <img src="images/1.jpg" />
    <img src="images/9.jpg" />
    <img src="images/2.jpg" />
    <img src="images/3.jpg" />
    <img src="images/4.jpg" />
    <img src="images/5.jpg" />
    <img src="images/6.jpg" />
    <img src="images/7.jpg" />
    <img src="images/8.jpg" />
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Store the picked coordinates in an array, so that you can compare the coordinates of each new image you place against the previous.

If the coordinates that you picked overlaps a previous image, pick new coordinates. Limit the number of tries so that if you can't place an image with say 1000 tries, you start over with the first image.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...