固定容器内任意个div填充算法
Posted 枫叶布
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了固定容器内任意个div填充算法相关的知识,希望对你有一定的参考价值。
<!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>
效果如下:
以上是关于固定容器内任意个div填充算法的主要内容,如果未能解决你的问题,请参考以下文章