-2

嘿伙计们,当 theBox 移出屏幕 (500x500) 时,我需要停止它,我不知道如何帮助?

 <style>
  #box { position: absolute; top: 0; left: 0; background-color: green; }
 </style>
 <script>
 onload = function() {
     var theBox = document.getElementById("box");
     function animate() {
     if ("theBox")
       theBox.style.left = (theBox.offsetLeft+5)+"px";
       theBox.style.top = (theBox.offsetTop+5)+"px";
     }
     setInterval(animate,100);
 }
 </script>
</head>
<body>
  <div id="box">The box</div>
</body>

4

2 回答 2

1

只需添加一个检查,看看下一步是否会使盒子达到或超过 500。此外,我添加了一个调用,以clearInterval()在盒子停止时停止计时器。

onload = function() {
    var timer;
    var theBox = document.getElementById("box");
    function animate() {
        if(theBox.offsetLeft+5 < 500 && theBox.offsetTop+5 < 500){
            theBox.style.left = (theBox.offsetLeft+5)+"px";
            theBox.style.top = (theBox.offsetTop+5)+"px";
        } else {
            clearInterval(timer);
        }
    }
    timer = setInterval(animate,100);
}
于 2013-10-24T15:42:53.133 回答
0

我添加了 if 语句来检查页面的高度是否高于框的偏移顶部:

 onload = function() {
 var theBox = document.getElementById("box");
 function animate() {
 if ("theBox")
   if(window.innerHeight > (theBox.offsetTop+25)){
      console.log(theBox.offsetTop+5)
      theBox.style.left = (theBox.offsetLeft+5)+"px";
      theBox.style.top = (theBox.offsetTop+5)+"px";
   }
 }
 setInterval(animate,100);
}

代码笔

于 2013-10-24T15:54:31.370 回答