<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>雪花下落</title>
</head>
<style>
.box{
height: 600px;
width: 800px;
border: 1px solid red;
position: relative;
overflow: hidden;
}
.box div{
position:absolute;
}
</style>
<body>
<div class="box" id="box">
</div>
<input type="button" value="生成雪花" id="btn" />
</body>
<script>
var box=document.getElementById("box");
var btn=document.getElementById("btn");
//生成雪花
function createSnow(l,t,s){
var newNode=document.createElement("div");
newNode.style.height=s+"px";
newNode.style.width=s+"px";
newNode.style.left=l+"px";
newNode.style.top=t+"px";
newNode.style.background="url('img/snow.png')";
newNode.style.backgroundSize="100% 100%";
box.appendChild(newNode);
startMove(newNode);
}
var time1=null;
var poY=0;
btn.onclick=function(){
setInterval(function(){
var le=parseInt(Math.random()*770);//随机生成位置及宽高
var to=parseInt(Math.random()*570);
var size=parseInt(Math.random()*10+20);
createSnow(le,to,size);
},100);
}
//雪花下落
function startMove(obj){
var poY=obj.offsetTop;//获取对象到顶部边宽的距离
var time2=null;
function move(){
poY++;
obj.style.top=poY+"px";
if(poY>600){//当雪花超出容器时的处理事件
clearInterval(time2);//清除计时器
box.removeChild(obj);//删除超出容器的节点对象
}
}
time2=setInterval(move,10);
}
</script>
</html>