原生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. html5手機(jī)觸屏touch事件介紹2. jsp實(shí)現(xiàn)簡(jiǎn)單用戶7天內(nèi)免登錄3. JSP動(dòng)態(tài)實(shí)現(xiàn)web網(wǎng)頁(yè)登陸和注冊(cè)功能4. HTML基礎(chǔ)知識(shí)總結(jié)5. 怎樣打開(kāi)XML文件?xml文件如何打開(kāi)?6. 讓 Asp 與 XML 交互7. ASP基礎(chǔ)入門(mén)第二篇(ASP基礎(chǔ)知識(shí))8. xml文件的結(jié)構(gòu)解讀第1/2頁(yè)9. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)10. 如何學(xué)習(xí)html的各種標(biāo)簽
