javascript运动问题:为什么top会一直在0和1徘徊呀?
迷茫
迷茫 2017-04-10 15:02:16
[JavaScript讨论组]
<!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徘徊呀?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(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;
黄舟

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号