2013-10-24 1 views
-2

안녕하세요, 제가 screeen (500x500)에서 이동할 때 theBox를 중지해야합니다. anyhelp하는 방법을 모릅니다?theBox를 중지해야합니다

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

답변

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); 
} 
+0

이 더 나은 && 대신에 사용 발견 && –

+0

@MrCode를 바운싱하고 싶습니다. –

0

와 페이지의 높이가 상자의 오프셋 정상보다 높은 경우 문을 확인하는 경우 :

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); 
} 

Code Pen

관련 문제