【发布时间】:2016-08-10 10:21:45
【问题描述】:
我正在创建一个网页,其中图像水平移动,直到按下“停止”按钮。
<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>
为什么会这样?
【问题讨论】:
-
var也在第二个代码中..
标签: javascript html dom-events