标签:doctype 图片 script gray var function text floor body
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title> </title> <style> #box{ height: 600px; width: 600px; border: 1px solid black; } </style> </head> <body> <input id="sr" /> <input type="button" id="bt" value="自动生成div" /> <div id="box"></div> </body> <script> window.onload = function () { var aBtn = document.getElementById(‘bt‘); var oBox = document.getElementById(‘box‘); var oSr = document.getElementById(‘sr‘); var str = ‘‘; var num = 0; var flag = 0; var aColor = [‘red‘, ‘blue‘, ‘green‘, ‘yellow‘, ‘purple‘, ‘pink‘, ‘gray‘]; //自动生成100个10*10的div aBtn.onclick = function () { str = ‘‘; num = oSr.value; //3 cnum = Math.round(Math.sqrt(num)); //2 lnum = Math.floor(num / cnum); //1 xnum = 0; if(num != 3){ for (var i = 0; i < lnum; i++) { for (var j = 0; j < cnum + xnum; j++) { if (i == lnum - 1) { xnum = num - cnum * lnum; } str += ‘<div style = "float:left;width:‘ + Math.floor(oBox.clientWidth / (cnum + xnum)) + ‘px;height:‘ + Math.floor(oBox.clientHeight / lnum) + ‘px;background:‘ + aColor[(i + j) % aColor.length] + ‘;"></div>‘; } str += ‘<br />‘; } }else{ for (var i = 0; i < cnum; i++) { for (var j = 0; j < lnum + xnum; j++) { if (i == cnum - 1) { xnum = num - cnum * lnum; } str += ‘<div style = "float:left;width:‘ + Math.floor(oBox.clientWidth / (lnum + xnum)) + ‘px;height:‘ + Math.floor(oBox.clientHeight / cnum) + ‘px;background:‘ + aColor[(i + j) % aColor.length] + ‘;"></div>‘; } str += ‘<br />‘; } } oBox.innerHTML = str; } } </script> </html>
效果如下:
标签:doctype 图片 script gray var function text floor body
原文地址:https://www.cnblogs.com/sghy/p/10337255.html