當前位置:軟件學堂 > 資訊首頁 > 網(wǎng)絡(luò)編程 > 編程其他 > 跟隨鼠標的旋轉(zhuǎn)背景JS代碼

跟隨鼠標的旋轉(zhuǎn)背景JS代碼

2012/10/23 18:23:45作者:佚名來源:網(wǎng)絡(luò)

移動端

【實例名稱】

跟隨鼠標的旋轉(zhuǎn)背景

【實例描述】

鼠標在頁面中移動的時候,會一直有一個旋轉(zhuǎn)的橢圓點跟隨它。本例學習如何實現(xiàn)這種效果。

【實例代碼】

<SCRIPT LANGUAGE="JavaScript">     var Clrs = new Array(6);                         //隨機的背景顏色,保存在一個數(shù)組中     Clrs[0] = 'ff0000';     Clrs[1] = '00ff00';     Clrs[2] = '000aff';     Clrs[3] = 'ff00ff';     Clrs[4] = 'fff000';     Clrs[5] = 'fffff0';     var yBase = 200;     var xBase = 200;     var step;     var currStep = 0;     var Xpos = 1;                                      //橫坐標變量     var Ypos = 1;                                      //縱坐標變量     if (document.all) {         function MoveHandler()         {             Xpos = document.body.scrollLeft+event.x;   //設(shè)置橫坐標             Ypos = document.body.scrollTop+event.y;    //設(shè)置縱坐標         }         document.onmousemove = MoveHandler;            //綁定鼠標的移動事件     }     function Comet()     {         if (document.all) {         yBase = window.document.body.offsetHeight / 4;         xBase = window.document.body.offsetWidth / 4;         }         if (document.all) {         for ( i = 0 ; i < starsDiv.all.length ; i++ ) {    //循環(huán)設(shè)置每個div的顯示位置         step = 3;         starsDiv.all[i].style.top = Ypos + yBase*Math.cos((currStep + i*4)/12)*Math.cos(0.7+currStep/200);         starsDiv.all[i].style.left = Xpos + xBase*Math.sin((currStep + i*3)/10)*Math.sin(8.2+currStep/400);         for (ai = 0; ai < Clrs.length; ai++) {         var c=Math.round(Math.random()*[ai]);              //獲取隨機的一個顏色值         }         starsDiv.all[i].style.background = Clrs[c];        //動態(tài)設(shè)置div的背景色            }         }         currStep += step;         setTimeout("Comet()", 5);                          //設(shè)置定時器-實現(xiàn)旋轉(zhuǎn)效果     }     Comet(); </script>  

【運行效果】

運行效果

【難點剖析】

本例的重點是旋轉(zhuǎn)背景所在的層。跟隨鼠標的旋轉(zhuǎn)背景由多個不同顏色的點組成,其中每個點是一個層(div),每個層的顏色不同。這些層的位置通過鼠標的坐標獲取,此處要注意層的位置使用“position:relative”,表示相對坐標,其坐標的原始點是這些層的父級節(jié)點“starsDiv”。

【源碼下載】

本實例JS代碼下載

 

標簽: 鼠標  JS代碼