美文网首页javaScript优化
随机生成10*10方块,并实现随机变色

随机生成10*10方块,并实现随机变色

作者: 丁小时候 | 来源:发表于2016-08-29 21:25 被阅读32次
闲来无聊,做个小东西玩 , 在body中随机生成10*10方块 , 并实现 随机 颜色


</br>

首先 介绍一个 新的 概念 文档碎片


</br>

1.概念

经JS操作DOM节点可以是节点的单位,让我们连接节点,能够createElement,createTextNode,然后,appendChild定在一起,然后再用appendChild或insertBefor加入到DOM树中.但假设要往DOM树中动态加入大量的节点.就会非常麻烦.并且每次都会刷新DOM。造成性能上的缺陷。

2.

效果图

我是效果图
<script type="text/javascript">

    function createBox(){
        console.log("createBox");
        //创建盒子的方法
        document.body.innerHTML = "";//先清空 body里面的内容
        //下面是 获取 浏览器的宽高
        var mWidth = document.documentElement.clientWidth || docuemnt.body.clientWidth;
        var mHeight = document.documentElement.clientHeight || document.body.clientHeight;
        // console.log(mWidth);
        // console.log(mHeight);
        //分 10 份
        var nDivWidth = mWidth/10;
        var nDivHeight = mHeight/10;
        // console.log(nDivWidth);
        // console.log(nDivHeight);
        //创建文档 碎片
        var oFrag = document.createDocumentFragment();

        for(var row=0;row<10;row++){
            for(var col=0;col<10;col++){
                var oDiv = document.createElement("div");

                oDiv.style.position = "absolute";//绝对 定位
                oDiv.style.height = nDivHeight +"px";
                oDiv.style.width = nDivWidth + "px";
                
                //每个div的位置
                oDiv.style.left = nDivWidth * col + "px";
                oDiv.style.top = nDivHeight * row + "px";


                //下面随机生RGB颜色值, 随机 数介于 0-256之间
                oDiv.style.background = "RGB("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")";
                //把每次创建 的div 追加给文档碎片
                oFrag.appendChild(oDiv);
            }
        }
        //最后一次性加 文档 碎片追加到body中,浏览器只渲染一次,提高性能
        document.body.appendChild(oFrag);
    }

    // 让这些盒子的背景色随机发生变化的方法
    function changeColor(){
        document.getElementsByTagName('div').item(Math.random()*100).style.background = "RGB("+ Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")";
    }

    // 当浏览器加载完成之后,运行fn方法 , 自动创建 背景颜色不同的10行10列小盒子,并且每隔两秒钟有一个小盒子颜色会变一次
    window.onload = function(){
        console.log("onload");
        createBox();
        window.setInterval(changeColor,100);
    }
    //方法名后面 不加括号, 加了括号 就表示 把这个方法的返回 值赋给 onresize事件了
    window.onresize = createBox;
</script>
-----------------------------markDown 实践中, 不喜忽喷----------------------------------------

相关文章

网友评论

    本文标题:随机生成10*10方块,并实现随机变色

    本文链接:https://www.haomeiwen.com/subject/xvqfettx.html