无法在onload属性

时间:2016-08-10 10:21:46

标签: javascript html javascript-events

我正在创建一个网页,其中图像水平移动,直到“停止我”为止。按下按钮。

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

为什么会这样?

2 个答案:

答案 0 :(得分:1)

这是一个范围问题:在属性中声明的变量不是全局的,例如:

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

在上面的示例中,在页面加载时,警报将显示消息hello。但是,当您单击该按钮时,您会收到此错误Uncaught ReferenceError: temp is not defined。这意味着变量temp不可访问(非全局)。

但是,为未声明的变量赋值会隐式地将其创建为全局变量,这就是为什么第二个示例正常工作:

答案 1 :(得分: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>