原生js實現星星閃爍的效果

來源:互聯網
上載者:User

標籤:body   ima   document   ++   cti   type   on()   不同的   get   

 星星閃爍的原理其實很簡單:

html代碼:

<body style="background:#000"><div id="stars_box"></div></body>
var stars_box=document.getElementById(‘stars_box‘);  //擷取id為star_box的元素var Obj=function(){}   //建立一個對象Obj.prototype.drawStar=function(){     //增加對象原型方法drawStarvar odiv=document.createElement(‘div‘);   //建立divodiv.style.width=‘7px‘;odiv.style.height=‘7px‘;odiv.style.position=‘relative‘;   //設定div為相對定位odiv.style.left=Math.floor(document.body.clientWidth*Math.random())+‘px‘;   //div的left值不能超出螢幕的寬度odiv.style.top=Math.floor(document.body.clientHeight*Math.random())+‘px‘;//div的left值不能超出螢幕的高度odiv.style.overflow=‘hidden‘;  //設定div的overflow為hiddenstars_box.appendChild(odiv);   //添加div到stars_box元素上var ostar=document.createElement(‘img‘);   //再建立img元素ostar.style.width=‘49px‘;ostar.style.height=‘7px‘;ostar.src=‘star.png‘;ostar.style.position=‘absolute‘;   //設定img為絕對位置ostar.style.top=‘0px‘;odiv.appendChild(ostar);   //把img添加到div中Play(ostar);    //實現動畫閃爍的方法Play();}function Play(ele){var i=Math.floor(Math.random()*7);  //為了使星星不同時閃爍,設定隨機值var timer=setInterval(function(){     //每100ms執行一次匿名方法if(i<7){ele.style.left=-i*7+‘px‘;i++;}else{i=0;}},100);}    //使用for迴圈建立30個不同的對象for(var i=0;i<30;i++){var obj=new Obj();obj.drawStar();}

星星閃爍靜態:

最後附上星星img圖:

 

原生js實現星星閃爍的效果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.