此代码的目的是使汽车和云从页面的两侧移动到每个图像的受尊重的相邻侧。我让他们搬家了。但他们继续通过浏览器观看空间。我想知道的是一种有效的方法来重置代码,使汽车和云回到原来的位置,然后再次移动。基本上,我想通过他们的代码循环汽车和云。我环顾四周,记得在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>
答案 0 :(得分: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>