点击生成随机色方块

学习js小练习,点击生成随机色小方块,当盒子装满时会弹出装满警告,再次点击小方块会生成删除事件

 HTML代码:

<body>
    <div class="box">
        <ul>
            <li class="add">+</li>
        </ul>
    </div>
</body>

CSS代码:

 .box {
        width: 500px;
        height: 500px;
        border: 2px solid orangered;
    }

    li {
        list-style: none;
    }

    .box ul {
        margin: 0;
        padding: 0;
    }

    .box li {
        float: left;
        margin: 10px;
        width: 80px;
        height: 80px;
        cursor: pointer;
    }

    .box .add {
        float: left;
        margin: 10px;
        width: 80px;
        height: 80px;
        color: #fff;
        font-size: 80px;
        text-align: center;
        line-height: 60px;
        background-color: #d7d7d7;
        cursor: pointer;
    }

JS代码:

<script>
    var add = document.querySelector(".add");
    var ul = document.querySelector("ul");
    var box = document.querySelector(".box");

    function randColor(element) {
        var randColor = "#" + ("00000" + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
        element.style.backgroundColor = randColor;
    }

    function checkOverflow(el) {
        var curOverflow = el.style.overflow;

        if (!curOverflow || curOverflow === "visible")
            el.style.overflow = "hidden";
        //先让溢出效果为 hidden 这样才可以比较 clientHeight和scrollHeight

        var isOverflowing = el.clientWidth < el.scrollWidth
            || el.clientHeight < el.scrollHeight;

        el.style.overflow = curOverflow;

        return isOverflowing;//不满返回false
    }

    add.addEventListener("click", function (e) {
        var li = document.createElement("li");
        randColor(li);
        ul.insertBefore(li, add);
        while (checkOverflow(box)) {
            ul.removeChild(ul.children[0]);
            alert("车满了,上不来了");
        }
        li.onclick = function () {
            li.remove();
        }
    })

</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奶油味的泡芙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值