使用DOM节点操作
1、周期性创建雪花
setInterval()
2、雪花出现的位置随机
function rand(m,n){return Math.floor(Math.random() * (n-m+1)) + m}
document.documentElement.clientWidth || document.body.clientWidth
3、控制雪花向下飘(移动的步径)
var step = 1;
4、移除超出窗口高度的雪花元素
document.documentElement.clientHeight || document.body.clientHeight
==================具体代码如下所示======================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>雪花飘落特效实现</title>
<style>
*{
margin:0;
padding:0;
}
body{
100%;
height: 100%;
overflow: hidden;
background-image: url('./images/snow.jpg');
}
</style>
</head>
<body>
</body>
<script>
//获取随机整数函数
function rand(m,n){
return Math.floor(Math.random() * (n - m + 1)) + m;
}
function setStyle(snowDiv){
snowDiv.innerHTML = "❄";
snowDiv.style.color = "#fff";
snowDiv.style.position = "absolute";
snowDiv.style.left = rand(0,document.documentElement.clientWidth || document.body.clientWidth) + 'px';
snowDiv.style.top = rand(0,200) + 'px';
snowDiv.style.fontSize = rand(16,50) + 'px';
snowDiv.style.opacity = Math.random();
document.body.appendChild(snowDiv);
}
//周期性创建雪花
setInterval(function(){
var snowDiv = document.createElement('div');
setStyle(snowDiv);
//设置雪花飘落的步径
var step = 1;
var run = setInterval(function(){
var newTop = snowDiv.offsetTop + step;
if(newTop >= document.documentElement.clientHeight || document.body.clientHeight){
document.body.removeChild(snowDiv);
clearInterval(run);
}
snowDiv.style.top = newTop + 'px';
},20)
},100)
</script>
</html>