jeudi 1 janvier 2015

Randomly positioned divs with no overlapping

All divs are being placed "randomly" like I need them to be, but they occasionally overlap. It's just a matter of chance. How can I prevent that from happening?


Can I achieve this by further developing the current javascript? Do I need consider a completely different approach?


I honestly don't know how to tackle this issue. Any guidance would be highly appreciated. Thanks.


html



<div id="box1" class="boxes">
<div id="text1">&nbsp;&nbsp;Lorem Ipsum Dolor Sit Amet&nbsp;&nbsp;</div>
</div>

<div id="box2" class="boxes">
<div id="text2">&nbsp;&nbsp;Lorem Ipsum Dolor Sit Amet&nbsp;&nbsp;</div>
</div>

<div id="box3" class="boxes">
<div id="text3">&nbsp;&nbsp;Lorem Ipsum Dolor Sit Amet&nbsp;&nbsp;</div>
</div>

<div id="box4" class="boxes">
<div id="text4">&nbsp;&nbsp;Lorem Ipsum Dolor Sit Amet&nbsp;&nbsp;</div>
</div>


css



.boxes {
position: absolute;
}

#text1 {
color: white;
font-family: "Times", Times New Roman, serif;
font-size: 16px;
font-weight: bold;
line-height: 24px;
background-color: black;
}

#text2 {
color: white;
font-family: "Times", Times New Roman, serif;
font-size: 16px;
font-weight: bold;
line-height: 24px;
background-color: blue;
}

#text3 {
color: white;
font-family: "Times", Times New Roman, serif;
font-size: 16px;
font-weight: bold;
line-height: 24px;
background-color: green;
}

#text4 {
color: white;
font-family: "Times", Times New Roman, serif;
font-size: 16px;
font-weight: bold;
line-height: 24px;
background-color: red;
}


javascript



function setRandomPos(elements,x,dx){
elements.each(function(){
fixLeft=(Math.floor(Math.random()*x)*10) + dx;
fixTop = (Math.floor(Math.random()*40)*10) + 180;
$(this).offset({
left: fixLeft,
top: fixTop
});
});
}

setRandomPos($(".boxes"),40,40);


Fiddle





Aucun commentaire:

Enregistrer un commentaire