无法在onload属性中声明变量
Unable to declare variable in onload attribute
我正在创建一个网页,其中图像水平移动,直到'stop me'按钮被按下。
<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>
为什么会这样?
这是一个作用域问题:属性中声明的变量不是全局的,例如:
<body onload = "var temp = 'hello'; alert(temp);">
<button onclick = "alert(temp);">Click</button>
</body>
在上面的示例中,在页面加载时,警报将显示消息hello
。但是,当你点击按钮,你得到这个错误Uncaught ReferenceError: temp is not defined
。这意味着变量temp
是不可访问的(不是全局的)。
试试这个
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>
相关文章:
- 使用同一对象中的其他变量声明变量
- 用||声明变量
- 使用javascript使用for循环声明变量
- JavaScript-用for循环项声明变量
- try声明变量的作用域
- 有没有一种方法可以使用函数参数的值来声明变量
- 在使用javascript再次声明变量之前,请先清除或删除该变量
- Javascript未声明变量
- 在Javascript中,我可以在声明变量之前使用它吗
- 在html文档的开头声明变量
- 按什么顺序声明变量和函数
- 如何以正确的方式在jQuery中声明变量
- 在 Angular 服务中接收函数的未声明变量
- 字典和声明变量
- 需要一些有关以以下样式声明变量的信息
- 在 jQuery 中使用常量声明变量
- 从外部文件在打字稿中声明变量得到引用错误:..未定义
- JavaScript,声明变量时混淆语法
- 在 javascript 函数和内存管理中声明变量
- Javascript 使用 if 语句声明变量