原生js實(shí)現(xiàn)星星閃爍效果
本文實(shí)例為大家分享了js實(shí)現(xiàn)星星閃爍效果的具體代碼,供大家參考,具體內(nèi)容如下
星星閃爍的原理其實(shí)很簡(jiǎn)單:
html代碼:
<body style='background:#000'> <div id='stars_box'></div></body>
js:
var stars_box=document.getElementById(’stars_box’); //獲取id為star_box的元素var Obj=function(){} //創(chuàng)建一個(gè)對(duì)象 Obj.prototype.drawStar=function(){ //增加對(duì)象原型方法drawStar var odiv=document.createElement(’div’); //創(chuàng)建div odiv.style.width=’7px’; odiv.style.height=’7px’; odiv.style.position=’relative’; //設(shè)置div為相對(duì)定位 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’; //設(shè)置div的overflow為hidden stars_box.appendChild(odiv); //添加div到stars_box元素上 var ostar=document.createElement(’img’); //再創(chuàng)建img元素 ostar.style.width=’49px’; ostar.style.height=’7px’; ostar.src=’star.png’; ostar.style.position=’absolute’; //設(shè)置img為絕對(duì)定位 ostar.style.top=’0px’; odiv.appendChild(ostar); //把img添加到div中 Play(ostar); //實(shí)現(xiàn)動(dòng)畫閃爍的方法Play(); } function Play(ele){ var i=Math.floor(Math.random()*7); //為了使星星不同時(shí)閃爍,設(shè)置隨機(jī)值 var timer=setInterval(function(){ //每100ms執(zhí)行一次匿名方法 if(i<7){ ele.style.left=-i*7 ’px’; i ; }else{ i=0; } },100); } //使用for循環(huán)創(chuàng)建30個(gè)不同的對(duì)象 for(var i=0;i<30;i ){ var obj=new Obj(); obj.drawStar(); }
星星閃爍靜態(tài)效果圖:
最后附上星星img圖:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. jsp實(shí)現(xiàn)簡(jiǎn)單用戶7天內(nèi)免登錄2. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識(shí))3. ASP中Server.HTMLEncode用法(附自定義函數(shù))4. ASP和PHP文件操作速度的對(duì)比5. ASP替換、保存遠(yuǎn)程圖片實(shí)現(xiàn)代碼6. adodb.recordset.open(rs.open)方法參數(shù)詳解7. jsp實(shí)現(xiàn)局部刷新頁面、異步加載頁面的方法8. 怎樣打開XML文件?xml文件如何打開?9. Spring依賴注入的三種方式實(shí)例詳解10. asp文件如何打開
