打个广告,最底下的公众号,可以每天领外卖红包、打车优惠券还有96折充值电费等,需要的可以关注一下哦
使用js实现雪花飘落效果,话不多说直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>snow</title>
<style>
body,html{
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
background: black;
}
.snow{
background: white;
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
}
</style>
</head>
<body>
<script>
//获取屏幕宽高
var windowWidth = window.screen.width;
var windowHeight = window.screen.height;
//创建雪花
function createSnow(){
var left = 0;
var top = 0;
//定义一个初始化随机数,使雪花在屏幕中
var left_random = Math.random() * windowWidth;
var top_random = Math.random()* windowHeight;
var div = document.createElement('div');
div.className = 'snow';
div.style.transform = 'scale('+(Math.random())+')'
document.body.appendChild(div);
//雪花飘落
setInterval(function () {
div.style.left = left_random + left +'px';
div.style.top = top_random + top +'px'
left += 0.2;
top += 0.2;
//如果雪花跑到屏幕外面了,让雪花重新返回屏幕顶部
if(left_random + left >= windowWidth){
left_random = Math.random();
left = 0;
}
if(top_random + top >= windowHeight){
top_random = Math.random();
top = 0;
}
},10)
}
for(var i = 0 ; i < 200 ; i++){
createSnow()
}
</script>
</body>
</html>
实现逻辑其实很简单,动态创建若干个div设置其样式变成雪花,通过setInterval定时器控制雪花移动,当雪花跑到屏幕外面重新让雪花的left或者top为0,使雪花重新回到最左或者最上面的位置,从而实现。
效果预览:
![](https://img-blog.csdn.net/20180409152648670?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hoenpjY18=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
代码优化:
看了一年前写的博客发现这个雪花效果还有优化的地方,由于left和top都会导致布局repaint,建议用translate代替,可以很明显的提高性能
然后就是关注一下我的公众号呀,就是底下这玩意,每天能领外卖红包、打车红包,还有96折充值电费等