<div class="codetitle"> <span><a style="CURSOR: pointer" data="30779" class="copybut" id="copybut30779" onclick="doCopy('code30779')"><u>複製程式碼</u></a></span> 程式碼如下:</div> <div class="codebody" id="code30779"> <br>//很有趣的浮動哦,不用太多程式碼,和大家分享下<br><br>隨機浮動<br><style type="text/css"><BR>#divimg{<BR>/*<BR>對圖片進行絕對定位<BR>*/<BR>position:absolute;<BR>}<BR></style> <br><br><br><div id="divimg"> <br><img src="../../resource/images/float.jpg" style="max-width:90%" style="max-width:90%" alt="js 圖片隨機不定向浮動的實作程式碼_javascript技巧" ><br> </div> <br><script language="javascript" type="text/ javascript"><BR>//取得圖片的所有div物件<BR>var divimg=document.getElementById("divimg");<BR>//設定起始位置<BR>var x=0,y=0; <BR>//設定圖片的前進速度<BR>var xSpeed=8,ySpeed=2;<BR>//設定圖片浮動高度和寬度<BR>var w=document.documentElement.clientWidth-205,h=document .body.clientHeight-108;<BR>//alert(w);<BR>function floatimg(){<BR>//比較是否達到邊界,如果到達邊界以後就改變圖片的方向為反向,如果未達到邊界則繼續向前<BR>if(x<0||x>w) xSpeed=-xSpeed;<BR>if(y<0||y>h) ySpeed=-ySpeed;<BR>x =xSpeed ;<BR>y =ySpeed;<BR>setTimeout("floatimg()",1000);<BR>var n=divimg.style.top=Math.round(Math.random()*h) "px"; <BR>var m=divimg.style.left=Math.round(Math.random()*w) "px";<BR>}<BR>floatimg();<BR></script><br><br><br> </div>