<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
<style>
body{background:url("bg.jpg");}
</style>
<script>
window.onload=function(){
sunX=0;
sunY=0;
directX=1;
directY=1;
function move(){
var oImg=document.getElementsByTagName("img")[0];
sunX+=directX;
sunY+=directY;
oImg.style.left=sunX+"px";
oImg.style.top=sunY+"px";
if(sunX+oImg.offsetWidth>=document.body.clientWidth||sunX<=0){
directX=-directX;
}
if(sunY+oImg.offsetHeight>=document.body.clientHeight||sunY<=0){
directY=-directY;
}
}
setInterval(move,100)
}
</script>
</head>
<body>
<p id="p2">
<img src="sun.gif" style="position:absolute;top:0px;left:0px;"/>
</p>
</body>
</html>
问题:为什么top会一直在0和1徘徊呀?
因为
document.body.clientHeight
的值是0
!你这获取浏览器宽高的方式兼容性不好, 试试这个:
图片是绝对定位的,已经脱离了文档流,不会将p2和body的高度给撑大,也就是说p2和body的height一直都为0。
给p2设置和图片一样高的height就能解决了