gpt4 book ai didi

javascript - JS-一段时间后水平移动图像

转载 作者:行者123 更新时间:2023-12-02 16:21:03 25 4
gpt4 key购买 nike

到目前为止一切都很顺利。我想让这个 hor() 函数在 20 秒后反转。原始的 hor() 函数抓取屏幕外的图像并将其从页面左侧水平移动到页面中心。我想创建一个函数,在 20 秒后执行相反的操作。 “20秒后”的部分是最让我悲伤的。如果您能向我展示一个新函数是什么样子,或者对当前函数进行“其他”添加,那就太好了。谢谢。

<script language="JavaScript" type="text/JavaScript">

var x = -500;
var y = 100;


function hor(val) {

if (x <= 500){
x = x + val;
document.getElementById("pos").style.left = x + "px";
setTimeout("hor(5)", 10);
}

}
</script>

<style type="text/css">
<!--
#pos {
position: absolute;
left: -500px;
top: 100px;
z-index: 0;
}

</style>


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

最佳答案

也许您可以尝试将脚本更改为:

// Define variables
var x = -500,
y = 100,
direction = 1;

// Function which moves "pos" element
function hor(val) {
// Move by specified value multiplied by direction
x += val * direction;

if(x > 500){
x = 500;
// Reverse direction
direction = -1;
} else if(x < -500){
x = -500;
// Reverse direction, once again
direction = 1;
}
// Move element
document.getElementById("pos").style.left = x + "px";

// Continue loop
setTimeout("hor("+val+")", 10);
}

此代码将继续将 pos 元素移动指定的值,直到 x 大于 500,此时它将切换方向,然后继续直到x达到-500,依此类推。

编辑:

这段代码将在 20 秒内解决这个问题(我原以为 500 像素的东西计算为 20 秒,哈哈)。

// Define variables
var x = -500,
y = 100,
direction = 1;
firstCall = true;
timeElapsed = 0;

// Function which moves "pos" element
function hor(val) {
// Don't let the first call count!
if(!firstCall)timeElapsed += 10;
else firstCall = false;

if(timeElapsed >= 2000){
// Reverse direction
direction *= -1;
timeElapsed = 0;
}

// Move by specified value multiplied by direction
x += val * direction;

// Move element
document.getElementById("pos").style.left = x + "px";

// Continue loop
setTimeout("hor("+val+")", 10);
}

关于javascript - JS-一段时间后水平移动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com