螢火蟲 <style type="text/css"> *{ padding: 0; margin: 0; } #bg{ background: url(img/bg.jpg) no-repeat; background-size: cover; width: 100%; height: 100%; ...
螢火蟲
<style type="text/css"> *{ padding: 0; margin: 0; } #bg{ background: url(img/bg.jpg) no-repeat; background-size: cover; width: 100%; height: 100%; position: fixed; } img { width: 18px; height: 18px; position: absolute; } </style> </head> <body> <div id="bg"> </div> </body> </html> <script src="public.js"></script> <script src="sport5.js"></script> <script> /* 確定構造函數 : FireFly 確定屬性 : 動態創建的每一個img 確定功能 : init 動態創建 運動 */ window.onload = function(){ var count = rand(30,80); for(var i = 0; i < count; i++){ new FireFly().init(); } } function FireFly(){ this.star = document.createElement("img"); this.init = function(){ this.star.src = "img/1.jpg"; this.star.style.left = rand(0,window.innerWidth - this.star.offsetWidth) + "px"; this.star.style.top = rand(0,window.innerHeight - this.star.offsetHeight) + "px"; document.body.appendChild(this.star); setInterval(function(){//定時器中的this是window,用bind去改變裡面的this,變為實例 this.fly(); }.bind(this),1000) } this.fly = function(){ move(this.star,{ "left" : rand(0,window.innerWidth - this.star.offsetWidth), "top" : rand(0,window.innerHeight - this.star.offsetHeight) }); } } /*var res = new FireFly(); res.init()*/ </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; }
sport5.js
//obj要操作的對象 //josn:要改變的屬性和目標值 //callback:回調函數;某件事件結束了,再調用我這個函數 //設置 寬 10 高 60 function move(obj,json,callback){ clearInterval(obj.timer); obj.timer = setInterval(function(){ var flag = true;//代表每一個屬性都到達目標值,不等於目標值不移除定時器 for(var attr in json){ var cur = 0; if(attr == "opacity"){ cur = parseFloat(getStyle(obj,attr)) * 100;//因為getComputedStyle取出來是字元串;所以parseFloat }else{ cur = parseInt(getStyle(obj,attr));//有單位 所以parseInt } var speed = (json[attr] - cur) / 10; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if(cur != json[attr]){ flag = false; } if(attr == "opacity"){ obj.style[attr] = (cur + speed) / 100; }else{ obj.style[attr] = cur + speed + "px"; } } // 寬 flag true 高 flag flase if(flag){ clearInterval(obj.timer);//代表著上一件事已經做完了 if(callback){ callback(); } } },30) } //獲取非行內元素樣式 實際值 function getStyle(obj,attr){ if(window.getComputedStyle){ return window.getComputedStyle(obj)[attr]; }else{ return obj.currentStyle[attr]; } }