<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>