JS-移动图像,暂停设置的时间,然后将图像向后移动

JS - Moving an image, pausing for set time, then moving image back

本文关键字:图像 移动 然后 设置 暂停 JS- 时间      更新时间:2023-09-26

我想创建一个像fly()这样的新函数,它将在暂停20秒后反转fly(()的操作原来的fly()函数将屏幕外的图像从页面的左侧水平移动到页面的中心,在那里图像保持静止。

我想创建一个函数,在图像保持静止20秒后将其移回屏幕外。"20秒后"的部分给了我最大的悲伤。如果你能告诉我一个新函数会是什么样子,或者在当前函数的基础上添加一个"else",那就太好了。

如果可能的话,根据我所拥有的保持简单,这样我就能理解。

<script language="JavaScript" type="text/JavaScript">
var x = -500;   
var y = 100;  

function fly(val) {
if (x <= 500){
x = x + val;    
document.getElementById("pos").style.left = x + "px";
setTimeout("fly(5)", 10);
}
}
</script>
<style type="text/css">
<!--
#pos {
position: absolute;
left: -500px;
top: 100px;
z-index: 0;
}
</style>

<body onLoad="setTimeout('fly(5)',5000)">
<div id="pos"> 
<a href="#"><img src="image.jpg"></a>
</div>

最简单的方法是在达到x=500的极限后使用setTimeout,正如您在else子句中所说的那样:

var x = -500;
function fly(val) {
    if (x <= 500){
       x = x + val;    
       document.getElementById("pos").style.left = x + "px";
       setTimeout("fly(5)", 10);
    }
    else {
       setTimeout("flyBack(5)", 20000);
    }
} 
function flyBack(val) {
    if (x >= -500){
       x = x - val;    
       document.getElementById("pos").style.left = x + "px";
       setTimeout("flyBack(5)", 10);
    }
}