原生JS實(shí)現(xiàn)螢火蟲(chóng)效果
本文實(shí)例為大家分享了JS實(shí)現(xiàn)螢火蟲(chóng)效果的具體代碼,供大家參考,具體內(nèi)容如下
上代碼之前,先看一下效果:
CSS部分(此處用元素模擬螢火蟲(chóng),背景可自行設(shè)置):
<style> .box{width: 4px;height: 5px;background: wheat;position: absolute;border-radius: 50%;} body{background: url(../img/bg.jpg) ;}</style>
JS部分:
<script>class Glowworm{ constructor(){ // 獲取屏幕的可視區(qū)域的寬高,用作將來(lái)的隨機(jī)范圍 this.clientW = document.documentElement.clientWidth; this.clientH = document.documentElement.clientHeight; // 假設(shè)螢火蟲(chóng)的寬高 this.w = 20; this.h = 20; } createEle(){ var div = document.createElement('div'); div.className = 'box'; document.body.appendChild(div); // 在創(chuàng)建元素之前一定得先生成隨機(jī)坐標(biāo) div.style.left = this.x + 'px'; div.style.top = this.y + 'px'; // 元素創(chuàng)建好之后,立即運(yùn)動(dòng) this.move(div); } randomPos(){ // 隨機(jī)生成坐標(biāo) this.x = random(0,this.clientW - this.w); this.y = random(0,this.clientH - this.h); } move(ele){ // 開(kāi)始運(yùn)動(dòng)之前,還得隨機(jī)生成目標(biāo) this.randomPos(); // 開(kāi)始運(yùn)動(dòng) move(ele,{ left:this.x, top:this.y },()=>{ // 一個(gè)動(dòng)畫(huà)結(jié)束后,重復(fù)開(kāi)啟當(dāng)前動(dòng)畫(huà),即可 this.move(ele); }) }}for(var i=0;i<60;i++){ // 先得到實(shí)例 var g = new Glowworm(); // 生成隨機(jī)坐標(biāo) g.randomPos(); // 再創(chuàng)建元素 g.createEle();}function random(a,b){ return Math.round(Math.random()*(a-b)+b);}</script>
最后需要引入一個(gè)運(yùn)動(dòng)函數(shù):原生JS封裝:帶有px的css屬性、透明度、且可以運(yùn)動(dòng)的函數(shù)。
function move(ele,obj,cb){ clearInterval(ele.t); ele.t = setInterval(() => { var i = true; for(var attr in obj){ if(attr == 'opacity'){ var iNow = getStyle(ele,attr) * 100; }else{ var iNow = parseInt(getStyle(ele,attr)); } let speed = (obj[attr] - iNow)/10; speed = speed < 0 ? Math.floor(speed) : Math.ceil(speed); // 只要有一個(gè)屬性沒(méi)到目標(biāo):絕對(duì)不能清除計(jì)時(shí)器 if(iNow !== obj[attr]){ i = false; } if(attr == 'opacity'){ ele.style.opacity = (iNow + speed)/100; }else{ ele.style[attr] = iNow + speed + 'px'; } } if(i){ clearInterval(ele.t); if(cb){ cb(); } // cb && cb(); } }, 30);}function getStyle(ele,attr){ if(ele.currentStyle){ return ele.currentStyle[attr]; }else{ return getComputedStyle(ele,false)[attr]; }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財(cái)務(wù)記賬管理系統(tǒng)2. Java 生成帶Logo和文字的二維碼3. asp讀取xml文件和記數(shù)4. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案5. XHTML 1.0:標(biāo)記新的開(kāi)端6. python中的socket實(shí)現(xiàn)ftp客戶端和服務(wù)器收發(fā)文件及md5加密文件7. xml中的空格之完全解說(shuō)8. python 實(shí)現(xiàn)圖片修復(fù)(可用于去水印)9. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?10. Javaweb工程運(yùn)行報(bào)錯(cuò)HTTP Status 404解決辦法
