-1

这段代码的目的是让汽车和云从页面的相对两侧移动到每个图像的受尊重的相邻侧。我已经让他们搬家了。但他们继续越过浏览器查看空间。我想知道的是一种有效的重置代码的方法,使汽车和云回到原来的位置,并再次移动。基本上,我想通过他们的代码循环汽车和云。我环顾四周,记得 2 年前在我的第一学期 JavaScript 课程中学到了一些东西,这可以帮助我做到这一点,只是我似乎找不到我要找的东西。

这就是我到此为止的内容。

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Car Animation</title>
    <style type="text/css">
        body {
            background-color: #AADDCC;
        }
        #imgMyCar{
        position:absolute;
        right:-600px;
        bottom:0px;

        }
        #imgMyCloud{
        position: absolute;
        left: -615px;
        top: 0px;

        }

    </style>
    <script>
    var carObject, cloudObject, counter;
    function setUp(){
    carObject=document.getElementById("imgMyCar");// set the carObject to the image tag
    cloudObject=document.getElementById("imgMyCloud");
    counter=-400;//initiliaze the counter to -600 so that the car is slightly off the right side of the screen.
    moveIt(); // call the moveIt function 

    }
    function moveIt(){
    counter=counter + 5;
    carObject.style.right=counter + "px";
    cloudObject.style.left=counter + "px";
    setTimeout(moveIt,10);

    }
    </script>
</head>
<body onload="setUp()">

    <img alt="car" id="imgMyCar" src="car1.png" />
    <img alt="cloud" id="imgMyCloud" src="clouds.png" />

</body>
</html>
4

1 回答 1

0

您可以使功能开关direction值。请检查更改。我希望你得到你想要的答案。

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Car Animation</title>
    <style type="text/css">
        body {
            background-color: #AADDCC;
        }
        #imgMyCar{
        position:absolute;
        right:-600px;
        bottom:0px;

        }
        #imgMyCloud{
        position: absolute;
        left: -615px;
        top: 0px;

        }

    </style>
    <script>
    var carObject, cloudObject, counter, direction;
    function setUp(){
    carObject=document.getElementById("imgMyCar");// set the carObject to the image tag
    cloudObject=document.getElementById("imgMyCloud");
    counter=-400;//initiliaze the counter to -600 so that the car is slightly off the right side of the screen.
    direction = 1; // set the direction
    moveIt(); // call the moveIt function 

    }
    function moveIt(){
        counter=counter + (direction * 5);
        carObject.style.right=counter + "px";
        cloudObject.style.left=counter + "px";
        if(counter > 500) {
            direction = -1;
        } else if(counter < -400) {
            direction = 1;
        }
        setTimeout(moveIt,10);

    }
    </script>
</head>
<body onload="setUp()">
    javascript animation

    <img alt="car" id="imgMyCar" src="car1.png" />
    <img alt="cloud" id="imgMyCloud" src="clouds.png" />

</body>
</html>
于 2013-05-31T15:38:50.220 回答