首页 > 其他分享 >自动生成div

自动生成div

时间:2023-02-13 11:48:14浏览次数:42  
标签:style li ul num 自动 var ulChild div 生成

<!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: 0px;
            padding: 0px;
        }
        
        .main {
            width: 1200px;
            margin: 0px auto;
        }
        
        button {
            margin: 10px 10px;
        }
        
        ul,
        li {
            list-style-type: none;
        }
        
        ul {
            position: relative;
        }
        
        li {
            width: 50px;
            height: 50px;
            background-color: red;
            color: white;
            font-size: 26px;
            position: absolute;
            text-align: center;
            line-height: 50px;
        }
    </style>
</head>

<body>
    <div class="main">
        <button>自动生成一个V字形</button>
        <ul>

        </ul>
    </div>
    <script>
        var ul = document.querySelector('ul');

        var btn = document.querySelector('button');

        btn.onclick = function() {
            ul.innerHTML = '';
            var num = Number(prompt('请输入您想组成V型的方块数'));
            for (var i = 0; i < num; i++) {
                var li = document.createElement('li');
                ul.appendChild(li);
                li.innerText = i;
            }
            var ulChild = ul.children;
            var helfNum = Math.floor(num / 2);
            for (var i = 0; i < num; i++) {
                if (i < Math.ceil(num / 2)) {
                    ulChild[i].style.left = i * 50 + 'px';
                    ulChild[i].style.top = i * 50 + 'px';
                } else {
                    ulChild[i].style.left = i * 50 + 'px';
                    ulChild[i].style.top = --helfNum * 50 + 'px';
                }
            }

        }
    </script>
</body>

</html>

 

标签:style,li,ul,num,自动,var,ulChild,div,生成
From: https://www.cnblogs.com/zhaofen/p/17115744.html

相关文章