JavaScript 實現下雪特效的示例程式碼
阿新 • • 發佈:2020-09-10
直接上程式碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>下雪效果實現</title> <link rel="stylesheet" type="text/css" href="reset.css"> <style type="text/css"> body,html{ overflow: hidden; } </style> </head> <body> <script type="text/javascript"> var snowflakes = { arr:[],// 陣列盛放元素 snowflake : [//雪花型別 '❉','❈','*','✲','❀','❃' ],snowflakeColor : [ //顏色庫 "red","green","#ccc123","#345232","#231111","#ab2322" ],random : function (num){ return Math.floor(Math.random()*num);// 獲得一個num-1的整數 },init : function (num){ // 最多個數 this.maxlength = num; // 邊界 this.maxWidth = (document.documentElement.clientWidth || document.body.clientWidth) + 20; // 邊界 this.maxHeight = (document.documentElement.clientHeight || document.body.clientHeight) + 20; this.create(); this.move(); },// 建立 create : function (){ var that = this; setInterval(function (){ // 當陣列中的數量,比最大數量要小的時候 開始建立 if( that.arr.length < that.maxlength){ var d = document.createElement("div"); // 內容和 顏色是隨機的 顏色和文字型檔裡面的 d.innerHTML = that.snowflake[that.random(that.snowflake.length)]; d.style.color = that.snowflakeColor[that.random(that.snowflakeColor.length)]; d.style.position = "absolute"; // 位置是隨機的 top(0- -99) left (0 - that.maxWidth*2/3-1) d.style.left = that.random(that.maxWidth*2/3) + "px"; d.style.top = -that.random(100) + "px"; // 速度 d.vx = 2+that.random(10); d.vy = 3+that.random(10); // 陣列新增元素,body 新增元素 document.body.appendChild(d); that.arr.push(d) } },20) },// 運動 move : function (){ var that = this; var arr = that.arr; setInterval(function (){ // 迴圈陣列中的每一個元素 for(var i = 0 ; i < arr.length ; i ++ ){ // 替換位置 arr[i].style.left = arr[i].offsetLeft + arr[i].vx + "px"; arr[i].style.top = arr[i].offsetTop + arr[i].vy + 'px'; // 判斷邊界 刪除元素 if (arr[i].offsetTop >= that.maxHeight || arr[i].offsetLeft >= that.maxWidth) { document.body.removeChild(arr[i]); arr.splice(i,1); } } },30) } } window.onload = function (){ snowflakes.init(100); } </script> </body> </html>
效果圖
以上就是JavaScript 實現下雪特效的示例程式碼的詳細內容,更多關於JavaScript 實現下雪特效的資料請關注我們其它相關文章!