js 图片随机不定向浮动的实现代码

复制代码 代码如下:

  //很有趣的浮动哦,不用太多代码,和大家分享下

  <html>

  <head>随机浮动

  <style type="text/css">

  #divimg{

  /*

  对图片进行绝对定位

  */

  position:absolute;

  }

  </style>

  </head>

  <body>

  <div id="divimg">

  <img src="../../resource/images/float.jpg" width="205" height="108">

  </div>

  <script language="javascript" type="text/javascript">

  //获取图片的所有div对象

  var divimg=document.getElementById("divimg");

  //设置起始位置

  var x=0,y=0;

  //设置图片的前进速度

  var xSpeed=8,ySpeed=2;

  //设置图片浮动高度和宽度

  var w=document.documentElement.clientWidth-205,h=document.body.clientHeight-108;

  //alert(w);

  function floatimg(){

  //比较是否达到边界,如果到达边界以后就改变图片的方向为反向,如果未达到边界则继续向前

  if(x<0||x>w) xSpeed=-xSpeed;

  if(y<0||y>h) ySpeed=-ySpeed;

  x+=xSpeed;

  y+=ySpeed;

  setTimeout("floatimg()",1000);

  var n=divimg.style.top=Math.round(Math.random()*h)+"px";

  var m=divimg.style.left=Math.round(Math.random()*w)+"px";

  }

  floatimg();

  </script>

  </body>

  </html>