学习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>