原生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)畫(huà)閃爍的方法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. python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析2. Python中讀取文件名中的數(shù)字的實(shí)例詳解3. 在idea中為注釋標(biāo)記作者日期操作4. 通過(guò)Ajax方式綁定select選項(xiàng)數(shù)據(jù)的實(shí)例5. JSP頁(yè)面的靜態(tài)包含和動(dòng)態(tài)包含使用方法6. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖7. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁(yè)8. .net如何優(yōu)雅的使用EFCore實(shí)例詳解9. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟10. ajax動(dòng)態(tài)加載json數(shù)據(jù)并詳細(xì)解析
