js生成div
阿新 • • 發佈:2017-09-14
mar innerhtml idt document epp pin arr image ont
1.生成100個div
要點根據索引值i計算left和top值,div逢10換行
HTML
<div id="box"> <!--<div>1</div>--> </div>
*{ margin: 0; padding: 0; } #box{ width: 500px; height: 500px; margin: 20px auto 0; position: relative; } #box div{ width: 30px; height: 30px; text-align: center; line-height: 30px; color: #fff; font-weight: bold; font-size: 16px; position: absolute; }
JS
var oBox=document.getElementById("box"); var arr_color=["darkmagenta","darkgreen","darkcyan","palegreen","plum","deeppink","deepskyblue"]; var str="";
//left計算:i%10*40
//top計算通過向下取整:Math.floor(i/10)*40
for (var i=0;i<100;i++) { str+="<div style=‘left:"+i%10*40+"px;top:"+Math.floor(i/10)*40+"px;background:"+arr_color[i%6]+";‘>"+i+"</div>"; } oBox.innerHTML=str;
js生成div