我试图设置div元素而不重叠,也像这样
有什么方法可以用css或javascript做到这一点? 在这段代码中,我实际上使用了很多边距。我认为有更好的办法。你可以帮帮我吗。
<div class='container'>
<div class='work1 round'></div>
<div class='work2 round'></div>
<div class='work3 round'></div>
<div class='work4 round'></div>
<div class='work5 round'></div>
<div class='work6 round'></div>
<div class='work7 round'></div>
</div>
.container {
width: 620px;
height: 400px;
margin: 0 auto;
background: rgba(200,200,200,1);
}
.round {
border-radius: 50%;
}
.work1 {
width: 80px;
height: 80px;
background: #ddd;
margin: 115px 0 0 270px;
position: absolute;
}
.work2 {
width: 75px;
height: 75px;
background: #ddd;
margin: 65px 0 0 140px;
position: absolute;
}
.work3 {
width: 55px;
height: 55px;
background: #ddd;
margin: 65px 0 0 80px;
position: absolute;
}
.work4 {
width: 90px;
height: 90px;
background: #ddd;
margin: 165px 0 0 193px;
position: absolute;
}
.work5 {
width: 77px;
height: 77px;
background: #ddd;
margin: 95px 0 0 213px;
position: absolute;
}
.work6 {
width: 20px;
height: 20px;
background: #ddd;
margin: 148px 0 0 213px;
position: absolute;
}
.work7 {
width: 28px;
height: 28px;
background: #ddd;
margin: 68px 0 0 213px;
position: absolute;
}
答案 0 :(得分:0)
如果您正在寻找随机生成器,请尝试使用此css -
.container {
width: 620px;
height: 400px;
margin: 0 auto;
background: rgba(200,200,200,1);
}
.round {
border-radius: 50%;
}
.work {
background: #ddd;
position: absolute;
}
用这个JS -
var checkOverLap = function(circles, mTop, mLeft, radius){
var x = mLeft + radius;
var y = mTop + radius;
for(var i = 0; i < circles.length; i++){
var distance = Math.ceil(Math.sqrt(Math.pow(x - circles[i].x, 2) + Math.pow(y - circles[i].y, 2)));
if (distance < (radius + circles[i].radius)){
//overlapped
return true;
}
}
return false;
}
$(function(){
var cont = $(".container");
cont.empty();
var circles = [];
for(var i = 0; i < 10; i++){
var div = $("<div>").addClass("work round");
var w = Math.floor((Math.random() * cont.width()) + 1) / 5;
var h = Math.floor((Math.random() * cont.height()) + 1) / 5;
var mTop = Math.floor((Math.random() * (cont.height() - h)) + 1);
var mLeft = Math.floor((Math.random() * (cont.width() - w)) + 1);
var radius = w > h ? h/2 : w/2;
if(checkOverLap(circles, mTop, mLeft, radius)){
i--;
continue;
}
$(div).css({
width: w > h ? h : w,
height: w > h ? h : w,
marginTop: mTop,
marginLeft: mLeft,
});
circles[circles.length] = {x:mLeft + radius, y:mTop + radius, radius: radius};
cont.append(div);
}
});
如果你愿意,你可以随意增加。这是小提琴链接 - http://jsfiddle.net/3paFX/5/
玩得开心!!!