原生JS實現(xiàn)螢火蟲效果
本文實例為大家分享了JS實現(xiàn)螢火蟲效果的具體代碼,供大家參考,具體內(nèi)容如下
上代碼之前,先看一下效果:
CSS部分(此處用元素模擬螢火蟲,背景可自行設(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ū)域的寬高,用作將來的隨機范圍 this.clientW = document.documentElement.clientWidth; this.clientH = document.documentElement.clientHeight; // 假設(shè)螢火蟲的寬高 this.w = 20; this.h = 20; } createEle(){ var div = document.createElement('div'); div.className = 'box'; document.body.appendChild(div); // 在創(chuàng)建元素之前一定得先生成隨機坐標(biāo) div.style.left = this.x + 'px'; div.style.top = this.y + 'px'; // 元素創(chuàng)建好之后,立即運動 this.move(div); } randomPos(){ // 隨機生成坐標(biāo) this.x = random(0,this.clientW - this.w); this.y = random(0,this.clientH - this.h); } move(ele){ // 開始運動之前,還得隨機生成目標(biāo) this.randomPos(); // 開始運動 move(ele,{ left:this.x, top:this.y },()=>{ // 一個動畫結(jié)束后,重復(fù)開啟當(dāng)前動畫,即可 this.move(ele); }) }}for(var i=0;i<60;i++){ // 先得到實例 var g = new Glowworm(); // 生成隨機坐標(biāo) g.randomPos(); // 再創(chuàng)建元素 g.createEle();}function random(a,b){ return Math.round(Math.random()*(a-b)+b);}</script>
最后需要引入一個運動函數(shù):原生JS封裝:帶有px的css屬性、透明度、且可以運動的函數(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); // 只要有一個屬性沒到目標(biāo):絕對不能清除計時器 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]; }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 使用css實現(xiàn)全兼容tooltip提示框2. div的offsetLeft與style.left區(qū)別3. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)4. Vue3使用JSX的方法實例(筆記自用)5. JavaScript數(shù)據(jù)類型對函數(shù)式編程的影響示例解析6. 詳解CSS偽元素的妙用單標(biāo)簽之美7. CSS代碼檢查工具stylelint的使用方法詳解8. 利用CSS3新特性創(chuàng)建透明邊框三角9. vue實現(xiàn)將自己網(wǎng)站(h5鏈接)分享到微信中形成小卡片的超詳細(xì)教程10. 不要在HTML中濫用div
