下雪效果 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 mar ...
下雪效果
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
雪花圖片(下方)