當(dāng)前位置:軟件學(xué)堂 > 資訊首頁 > 網(wǎng)絡(luò)編程 > 編程其他 > JS實現(xiàn)晃動的圖片

JS實現(xiàn)晃動的圖片

2012/11/8 10:13:34作者:佚名來源:網(wǎng)絡(luò)

移動端

【實例名稱】

JS實現(xiàn)晃動的圖片

【實例描述】

文字可以實現(xiàn)左右滾動,圖片也可以實現(xiàn)左右移動。本例介紹一個圖片左右移動的特效。

【實例代碼】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>標(biāo)題頁-學(xué)無憂(www.wangbatian.cn)</title> <script language="JavaScript"> step = 0; obj = new Image();        //創(chuàng)建圖片對象 function anim(xp,xk,smer) //smer 代表晃動方向 {    obj.style.left = x;    x += step*smer;   if (x>=(xk+xp)/2) {     if (smer == 1) step--; //往左移動        else step++;     }  else {     if (smer == 1) step++; //往右移動        else step--;     }    if (x >= xk) {      //如果已經(jīng)到右邊界,則反向晃動        x = xk;        smer = -1;       }

  if (x <= xp) {   //如果一定到左邊界,則反向晃動        x = xp;        smer = 1;       }   setTimeout('anim('+xp+','+xk+','+smer+')', 40); //設(shè)置定時器,實現(xiàn)不斷晃動效果 }

function moveLR(objID,movingarea_width,c) {

  if (navigator.appName=="Netscape") window_width = window.innerWidth;      else window_width = document.body.offsetWidth;   //獲取窗體的寬度   obj = document.images[objID];     image_width = obj.width;                            //獲取圖像的寬度     x1 = obj.style.left;                                //獲取圖像的X坐標(biāo)   x = Number(x1.substring(0,x1.length-2));             //去掉后面的像素標(biāo)記“px”   if (c == 0) {                                           if (movingarea_width == 0) {                  //沒有設(shè)置移動區(qū)域的情況       right_margin = window_width - image_width;          anim(x,right_margin,1);                  //開始晃動圖片    }              else { right_margin = x + movingarea_width - image_width;     if (movingarea_width < x + image_width) window.alert("No space for moving!");           else anim(x,right_margin,1);   }    }    else {        if (movingarea_width == 0)        //沒有設(shè)置移動區(qū)域的情況           right_margin = window_width - image_width;     else {        x = Math.round((window_width-movingarea_width)/2);     right_margin = Math.round((window_width+movingarea_width)/2)-image_width; //獲取可以移動的空間    }   anim(x,right_margin,1);    }       } </script> <img src="http://www.baidu.com/img/logo.gif" name="img1" style='position: absolute; top: 50px; left: 213px;' border=0 id="myImg"> <script language="JavaScript">   setTimeout("moveLR('myImg',400,1)",10); </script> </head> <body> </body> </html>

 

 

【運行效果】

 晃動的圖片運行效果

【難點剖析】

本例的重點是定時器和隨機數(shù)的應(yīng)用。定時器用來不斷移動圖片,隨機數(shù)的獲取是使用“Math.random”函數(shù)?!癕ath.round”是四舍五人函數(shù),返回一個偽隨機數(shù)(0~1之間的double數(shù))。

【源碼下載】

為了JS代碼的準(zhǔn)確性,請點擊:JS實現(xiàn)晃動的圖片 進(jìn)行本實例源碼下載 

標(biāo)簽: JS實現(xiàn)  圖片