下雪效果

 1 <style>
 2     * {
 3         margin: 0;
 4         padding: 0;
 5     }
 6     #box {
 7         width: 1000px;
 8         height: 600px;
 9         background: #000000;
10         border: 5px solid red;
11         margin: 20px auto;
12         position: relative;
13     }
14     img{
15         position: absolute;
16     }
17 </style>
18
19 <body>
20     <div id="box"></div>
21 </body>
22 </html>
23 <script src="public.js"></script>
24 <script>
25     /*
26          分析构造函数   Snow
27          属性 : img   box
28          方法 :  雪花创建init   移动
29     */
30     window.onload = function(){
31         setInterval( function(){
32             new Snow().init().move();
33         },800 )
34     }
35     function Snow(){
36         this.img = document.createElement("img");
37         this.box = $id("box");
38         this.init = function(){//雪花创建
39             this.img.src = "img/snow.png";
40             this.box.appendChild( this.img );
41             this.img.width=this.img.height = rand(10,15);
42             this.img.style.left = rand(0,this.box.offsetWidth-this.img.offsetWidth) + "px";
43             this.img.style.top = -this.img.offsetHeight+"px";
44             return this;
45         }
46         this.move = function(){
47             //定义雪花移动的速度
48             var speedX = -rand(1,5);
49             var speedY = rand(1,5);
50             this.timer = setInterval( function(){
51                 this.img.style.left = this.img.offsetLeft +  speedX + "px";
52                 this.img.style.top = this.img.offsetTop + speedY + "px";
53                 if( this.img.offsetLeft < -this.img.offsetWidth || this.img.offsetTop > this.box.offsetHeight ){
54                     //clearInterval( this.timer );
55                     this.img.remove();
56                 }
57             }.bind(this),30 )
58         }
59     }
60 </script>

public.js

function $id(id){//给我一个id名,返回一个这个id的元素
    return document.getElementById(id);
}
//求随机数
function rand(min,max){
    return Math.round(Math.random()*(max - min) + min);
}

//随机的16进制颜色
function getColor(){
    var str = "0123456789ABCDEF";//十六进制字符串
    var color = "#";
    for(var i = 0; i <= 5; i++){//取6个数
        color += str.charAt(rand(0,15));
        //rand(0,15)随机0-15之间的数,作为charAt()的下标,取出下标对应的字符
    }
    return color;
}
function zero(val){
    return val < 10 ? "0" + val : val;
}
//时间差
function diff(start,end){//2000-2018  2018 - 2000
    //console.log(start.getTime());
    return Math.abs(start.getTime() - end.getTime())/1000;
}
View Code

雪花图片(下方)

01-06 18:38