js用for循环将小方块摆成V型方法三--小技巧

<!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>
        div {
            width: 50px;
            height: 50px;
            background: red;
            position: absolute;
            font-size: 20px;
            color: #fff;
            text-align: center;
            line-height: 50px;
        }
        #box{
            position: relative;
        }
    </style>
</head>

<body>
    <input type="text" id="pt">
    <button id="btn">按钮</button>
    <section id="box"></section>
    <script>

        // 1、静态
        // 2、动态

        var pt = document.getElementById('pt');
        var btn = document.getElementById('btn');
        var box = document.getElementById('box');

        btn.onclick = function () {
			box.innerHTML = "";  //清空
            var len = parseInt(pt.value);
            var t = 0;
            for (var i = 0; i < len; i++) {
                // 当 i< len / 2  top 值是增加的 否则是减少的  但是 left值是一直增加的
                if (i < len / 2) {
                    // t = i;
                    box.innerHTML += '<div style="left:' + i * 50 + 'px;top:' + i * 50 + 'px">'+(i+1)+'</div>';
                } else {
                    //t = len - i - 1;   // 12 -0  12- 1  12- 2 
                    box.innerHTML += '<div style="left:' + i * 50 + 'px;top:' +(len - i - 1) * 50 + 'px">'+(i+1)+'</div>';
                }
              
            }

        }

    </script>
</body>

</html>

posted @ 2021-08-25 12:35  JackieDYH  阅读(3)  评论(0编辑  收藏  举报  来源