js随机生成多个div并每隔10个换行2017-09-30 21:14
假设我们要使用js生成100个div标签。
那么只需要用到for循环,累积div起来就可以了。
然后将其填充到年月有.box样式的div里面。
再获取.box下面的所有div,使用find()即可。
再次使用for来遍历刚生成的100个div标签。
设置它们的left以及top,这里是因为我们已经定义了一些样式,所以要这样做。
以下为源码: html代码
js生成100个div.box div{
width: 50px;
height: 50px;
line-height: 50px;
border-radius:4px;
background: #1abc9c;
position: absolute;
left: 0;
top: 0;
font-size: 24px;
color: white;
font-weight: bold;
text-align: center;
}
$(document).ready(function(e) {
var str="";
for(var i=1;i<=100;i++ ){
str+="
}
$(".box").html(str);
//上面为生面100个div标签
var div=$(".box").find("div");
for(var i=1;i<=div.length;i++){
div[i].style.left=(i%10)*60+"px";
div[i].style.top=Math.floor(i/10)*60+"px";
}
});
亲自测试一下
关键的就是“i%10”以及“Math.floor(i/10)”这两上地方。
如果需要其他数值换行,只需将“10”改为想要的值即可。