原生JS 实现方块掉落
效果图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box{
width:500px;
height: 700px;
margin: 0 auto;
border: 1px solid #000;
position: relative;
}
#box>.boxchider{
box-sizing: border-box;
width: 100px;
float: left;
position: relative;
height:100%;
}
.claerfix::after{
content:"";
display:block;
visibility:hidden;
clear:both;
}
</style>
</head>
<body>
<div>
<h1 id="title"></h1>
<div id="box" class="claerfix">
<div class="boxchider" >
</div >
<div class="boxchider">
</div>
<div class="boxchider" >
</div>
<div class="boxchider" >
</div>
<div class="boxchider" >
</div>
</div>
</div>
<script>
var box=document.getElementById("box");
var listbox=document.getElementsByClassName("boxchider");
function Move(){
var createdDiv=document.createElement("div");
var num = Math.floor(Math.random() * 5);
createdDiv.style.position='absolute';
createdDiv.style.width=100+"px";
createdDiv.style.height=70+"px";
createdDiv.style.background="#ccc";
var chider=listbox[num];
if(chider.clientHeight<=70) {
} else{
document.getElementById("title").innerHTML=num;
chider.appendChild(createdDiv);
for (let i = 0; i <chider.clientHeight-70; i++) {
setTimeout(()=>{
createdDiv.style.top=i+"px";
},i*7);
}
chider.style.height=chider.clientHeight<=70?70+"px":chider.clientHeight-70+"px"
}
}
setInterval(() => {
Move();
},1000);
</script>
</body>
</html>