本文實(shí)例為大家分享了js實(shí)現(xiàn)星星閃爍效果的具體代碼,供大家參考,具體內(nèi)容如下
星星閃爍的原理其實(shí)很簡單:
html代碼:
1
2
3
|
< body style = "background:#000" > < div id = "stars_box" ></ div > </ body > |
js:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
var stars_box=document.getElementById( 'stars_box' ); //獲取id為star_box的元素 var Obj= function (){} //創(chuàng)建一個(gè)對象 Obj.prototype.drawStar= function (){ //增加對象原型方法drawStar var odiv=document.createElement( 'div' ); //創(chuàng)建div odiv.style.width= '7px' ; odiv.style.height= '7px' ; odiv.style.position= 'relative' ; //設(shè)置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' ; //設(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為絕對定位 ostar.style.top= '0px' ; odiv.appendChild(ostar); //把img添加到div中 Play(ostar); //實(shí)現(xiàn)動畫閃爍的方法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è)不同的對象 for ( var i=0;i<30;i ){ var obj= new Obj(); obj.drawStar(); } |
星星閃爍靜態(tài)效果圖:
最后附上星星img圖:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/u011927449/article/details/104038393