html文件,碰到边缘自动弹回
<html>
<head>
<title>小太阳</title>
<script language="javaScript">
//定义全局变量,两个方向
directionX=1;//x轴的方向
directionY=1;//y轴的方向
sunX=0;//小太阳的坐标x
sunY=0;//小太阳的坐标y
speed=2;
function sunMove(){
var sundiv=document.getElementById('sundiv');
sunX+=directionX*speed;
sunY+=directionY*speed;
sundiv.style.top=sunY+"px";
sundiv.style.left=sunX+"px";
//x方法(offsetWidth可以返回,当前这个对象的实际宽度)
if(sunX+sundiv.offsetWidth>=document.body.clientWidth||sunX<=0){
directionX=-directionX;
}
//判断y
if(sunY+sundiv.offsetHeight>=document.body.clientHeight||sunY<=0){
directionY=-directionY;
}
}
setInterval("sunMove()",10);
</script>
</head>
<body style="background-image:url('img/bizhi.jpg')">
<div id="sundiv" style="position:absolute;top:10px;left:10px;width:20px;">
<img src="img/sun.gif" style="width:80px;"/>
</div>
</body>
</html>