无法在onload属性中声明变量

Unable to declare variable in onload attribute

本文关键字:声明 变量 属性 onload      更新时间:2023-09-26

我正在创建一个网页,其中图像水平移动,直到'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>