2016-08-10 2 views
0

'중지'버튼을 누를 때까지 이미지가 수평으로 이동하는 웹 페이지를 만들었습니다.onload 속성에서 변수를 선언 할 수 없습니다.

<html> 
    <head> 
     <script> 
      var count = 0; 
      function move(){ 
       image = document.getElementsByTagName("img")[0]; 
       count++; 
       image.style.left = count; 
      } 
     </script> 
    </head> 
    <body onload = "var temp = setInterval(move,1)"> 
     <img src = "facebook_icon.png" style = "position:absolute; left = 0; top:0;"> 
     <br> 
     <button onclick = "clearInterval(temp);">Click here to stop the loop.</button> 
    </body> 
</html> 

onload 특성에서 var 키워드를 제거하면 코드가 제대로 실행됩니다. 새 코드 : -

<html> 
    <head> 
     <script> 
      var count = 0; 
      function move(){ 
       image = document.getElementsByTagName("img")[0]; 
       count++; 
       image.style.left = count; 
      } 
     </script> 
    </head> 
    <body onload = "temp = setInterval(move,1)"> 
     <img src = "facebook_icon.png" style = "position:absolute; left = 0; top:0;"> 
     <br> 
     <button onclick = "clearInterval(temp);">Click here to stop the loop.</button> 
    </body> 
</html> 

왜 그렇게 되나요?

+0

'var'도 두 번째 코드에 .. –

답변

1

그것은 범위의 문제이다 : 속성에서 선언 된 변수는, 예를 글로벌되지 않습니다 : 위의 예에서

<body onload = "var temp = 'hello'; alert(temp);"> 
    <button onclick = "alert(temp);">Click</button> 
</body> 

, 페이지로드, 경고 메시지 hello 표시됩니다. 그러나 단추를 클릭하면이 오류 Uncaught ReferenceError: temp is not defined이 표시됩니다. 즉 변수 temp에 액세스 할 수 없습니다 (전역이 아님). 두 번째 예는 잘 작동하는 이유

그러나, 선언되지 않은 변수에 값을 할당하는 암시 적으로 전역 변수로 생성, 그건 :

0

이 하나를 시도하십시오.

CSS

<style> 
#container { 
      width: 400px; 
      height: 400px; 
      position: relative; 
      background: yellow; 
     } 
     #animate { 
      width: 50px; 
      height: 50px; 
      position: absolute; 
      background-color: red; 
     } 
    </style> 

HTML

<div id="container"> 
      <img src="images/up.png" id="animate" /> 
     </div> 
     <br/> 
     <br/> 
     <br/> 

     <button onclick="myStopFunction()">Click here to stop the loop.</button> 

스크립트

<script type="text/javascript"> 
     function myMove() { 
      var elem = document.getElementById("animate"); 
      var pos = 0; 
      var id = setInterval(frame, 1); 
      function frame() { 
       if (pos == 350) { 
        clearInterval(id); 
       } else { 
        pos++; 
        elem.style.top = pos + 'px'; 
        elem.style.left = pos + 'px'; 
       } 
      } 
     } 
     function myStopFunction() { 
      var elem = document.getElementById("animate"); 
      clearInterval(myMove()); 
     } 
    </script> 
관련 문제