在页面加载 - 防止随机定位的div彼此重叠

时间:2014-11-27 13:37:18

标签: jquery random

我有一些代码可以在页面加载时随机将DIV放在屏幕上。见下面的小提琴。我正在努力的是如何使它们不相互重叠......如果可能的话?

jsFiddle link example

代码示例内联如下:

<style>
body, html {
background: #fff;
height: 100%;
width: 100%;
padding:0; margin:0;
overflow: hidden;
}
div { 
height: auto;
float: left;
margin: 5px;
display: block;
position: absolute;
}   
.decs img {
width: 100%;
height: auto;
}
</style>

<body>

<div class="decs"><img src="images/dec1f.png"></div>
<div class="decs"><img src="images/dec2f.png"></div>
<div class="decs"><img src="images/dec3f.png"></div>
<div class="decs"><img src="images/dec4f.png"></div>
<div class="decs"><img src="images/dec1f.png"></div>
<div class="decs"><img src="images/dec2f.png"></div>
<div class="decs"><img src="images/dec3f.png"></div>
<div class="decs"><img src="images/dec4f.png"></div>
<div class="decs"><img src="images/dec1f.png"></div>
<div class="decs"><img src="images/dec2f.png"></div>
<div class="decs"><img src="images/dec3f.png"></div>
<div class="decs"><img src="images/dec4f.png"></div>
<div class="decs"><img src="images/dec1f.png"></div>
<div class="decs"><img src="images/dec2f.png"></div>
<div class="decs"><img src="images/dec3f.png"></div>
<div class="decs"><img src="images/dec4f.png"></div>



<script type="text/javascript">
$(".decs").each(function(i) {

var e = $(this);

var posx = Math.max(0, Math.min(100, Math.ceil(Math.random() * 100)));
var posy = Math.max(0, Math.min(100, Math.ceil(Math.random() * 100)));
var widthval = Math.max(0, Math.min(15, Math.ceil(Math.random() * 100)));

e.css({'left':posx+'%','top':posy+'%','width':widthval+'%'});

});

</script>   
</body>

有什么想法吗?

0 个答案:

没有答案