我编写了一个img元素,以通过主体中的setInterval(fall,1000)函数触发的parseInt(its.style.top)“落下”窗口。

触发Moves()函数后,将发生错误,并且fall()函数停止被调用。在img s.style.left> = r.style.width之后,是否有一个if语句用于Moves()函数再次调用setInterval(fall,1000)?

谢谢! :-)

<html>
<body onload="setInterval(fall,1000)" onkeydown="Moves()">

<img id="square" style="position:absolute; left:10px; top:0px;
width:50px; height:50px; background-color:red;" />

<img id="rectangle" style="position:absolute; left:10px; top:130px;
width:150px; height:10px; background-color:blue;" />

<script>

function fall(){
var s = document.getElementById("square");
s.style.top = parseInt(s.style.top) + 25 + 'px';


var r = document.getElementById("rectangle");
r.style.top=130 + 'px';

if(s.style.top>=r.style.top){s.style.top=r.style.top;}
}

function Moves(){
var s = document.getElementById("square");
if (event.keyCode==39) {
s.style.left = parseInt(s.style.left)+10+'px';}

var r = document.getElementById("rectangle");
r.style.width=150 + 'px';

if(s.style.left>=r.style.width){setInterval(fall,1000);}
}

</script>

</body> </html>

最佳答案

我相信这是您想要做的:

<html>
<body onload="setTimeout(fall,1000)" onkeydown="Moves()">

    <img id="square" style="position:absolute; left:10px; top:0px;
    width:50px; height:50px; background-color:red;" />

    <img id="rectangle" style="position:absolute; left:10px; top:130px;
    width:150px; height:10px; background-color:blue;" />

    <script>
        var over_edge = false;
        var can_fall = true;

        function fall(){
            var s = document.getElementById("square");
            s.style.top = parseInt(s.style.top) + 25 + 'px';


            var r = document.getElementById("rectangle");
            //r.style.top=130 + 'px';

            if(!over_edge) {
                if(parseInt(s.style.top) >= parseInt(r.style.top) - parseInt(s.style.height)) {
                    s.style.top = parseInt(r.style.top) - parseInt(s.style.height);
                    can_fall = false;
                }
            }
            if(can_fall || over_edge)
                setTimeout(fall, 1000);
        }

        function Moves(){
            var s = document.getElementById("square");
            if (event.keyCode==39) {
                s.style.left = parseInt(s.style.left)+10+'px';}

                var r = document.getElementById("rectangle");
                //r.style.width=150 + 'px';

                if(parseInt(s.style.left) >= parseInt(r.style.left) + parseInt(r.style.width)) {
                    if(!over_edge) {
                        over_edge = true;
                        fall();             // trigger falling over the edge but only once
                    }
                }
            }

    </script>
</body>
</html>

09-26 10:10