码迷,mamicode.com
首页 > 编程语言 > 详细

固定容器内任意个div填充算法

时间:2019-01-30 12:47:20      阅读:152      评论:0      收藏:0      [点我收藏+]

标签: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>

效果如下:

技术分享图片

固定容器内任意个div填充算法

标签:doctype   图片   script   gray   var   function   text   floor   body   

原文地址:https://www.cnblogs.com/sghy/p/10337255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!