javascript运动问题:为什么top会一直在0和1徘徊呀?

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


<div id="div2">
 <img src="sun.gif" style="position:absolute;top:0px;left:0px;"/>
</div>


</body>
</html>

图片描述

问题:为什么top会一直在0和1徘徊呀?

阅读 3.5k
2 个回答

因为document.body.clientHeight的值是0!

你这获取浏览器宽高的方式兼容性不好, 试试这个:

var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

图片是绝对定位的,已经脱离了文档流,不会将div2和body的高度给撑大,也就是说div2和body的height一直都为0。
给div2设置和图片一样高的height就能解决了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题