自动生成十个盒子

代码(两种方法)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        .box{
           width:50px;
           height:50px;
           background:orange; 
           position: absolute;
        }
        /* .box:nth-child(1){
            left:0;
            top:0;
        }
        .box:nth-child(2){
            left:50px;
            top:50px;
        }
        .box:nth-child(3){
            left:100px;
            top:100px;
        } */
    </style>
</head>
<body>
    
<div id="app"></div>

    <script>
        var box = document.getElementsByClassName('box');
        // box[0].style.cssText ='left:0;top:0'; 
        // box[1].style.cssText ='left:50px;top:50px'; 
        // box[2].style.cssText ='left:100px;top:100px'; 
        // box[3].style.cssText ='left:150px;top:150px'; 
        // box[4].style.cssText ='left:200px;top:200px'; 

        // for(var i=0;i<box.length;i++){
        //     box[i].style.cssText = 'left:'+50 *i + 'px;top:' + 50 * i + 'px;'
        // }
        for(var i=0;i<10;i++){//  0123456789
            document.body.innerHTML += '<div class="box" style="left:'+50 * i+'px;top:'+50 * i+'px;"></div>'
        }

    </script>
</body>
</html>

 

效果:

 

posted @ 2020-07-03 13:16  石海莹  阅读(320)  评论(0编辑  收藏  举报