原生JS实现雪花飘落的效果

目录

1.代码

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- 设置网站图标favicon -->
  <link rel="shortcut icon" href="favicon.ico" type="image/x-con" />
  <title>❄雪❄</title>
</head>
<style>
  *{ padding: 0;margin: 0; } /*所有元素的内边距,外边距都设置为0(HTML元素有自己默认的样式)*/
  body {
    width: 100%;
    height: 100%;
    background: url("bg.jpg") no-repeat;
    background-size: cover; /*保持图像的纵横比并将图像完全覆盖父容器*/
    overflow: hidden;       /*内容溢出就隐藏*/
  }
</style>
<body>
  <div id="main"></div>
  <script>
    const Scene = function(){};  //创建一个Scene对象
    //为这个对象添加一个具有一个参数的原型方法
    Scene.prototype.draw=function(snow){
      let fallingHeight = 0;                                   //雪花下落的高度
      let screenWidth = document.documentElement.clientWidth;  //获取浏览器窗口文档显示区域的宽度,不含滚动条
      let screenHeight = document.documentElement.clientHeight;//获取浏览器窗口文档显示区域的高度,不含滚动条
      snow.style.color="#fff";                                 //设置雪花颜色为白色
      snow.style.fontSize=12+Math.ceil(Math.random()*14)+'px'; //随机设置雪花大小
      snow.style.opacity=(Math.ceil(Math.random()*3)+7)/10+""; //随机设置雪花的透明度
      let startPos=Math.ceil(Math.random()*screenWidth);
      snow.style.left=startPos+'px';                           //随机设置雪花开始出现的水平位置
      setInterval(function(){
        //雪花每300ms下降10px,当下降距离大于screenHeight,雪花消失
        if(fallingHeight<screenHeight){
          snow.style.top=fallingHeight+'px';
          snow.style.left=startPos+Math.ceil(Math.random()*8)+'px'; //雪花向左随机移动一段距离
          fallingHeight+=10;
        }else{
          snow.style.display = 'none';
        }
      },300)
    }
    let main = document.getElementById('main')
    //用定时器每500ms创建一个雪花
    setInterval(function() {
      let snow = document.createElement('div') //创建div
      snow.innerHTML ="❄"                      //div的内容设置为雪花图形
      snow.style.position='absolute'            //设置div为绝对定位
      main.append(snow)                         //把创建好的div放进main容器中
      let scene = new Scene()                   //创建Scene对象
      scene.draw(snow)                          //执行Scene对象的draw方法
    },500)
  </script>
</body>
</html>

同一目录下放两张图片:bg.jpgfavicon.ico

bg.jpg

favicon.ico

2.效果

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漂流の少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值