您的位置:首页 > Web前端 > JavaScript

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

2013-07-02 00:00 776 查看
//很有趣的浮动哦,不用太多代码,和大家分享下
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: