gpt4 book ai didi

javascript - 如何仅在动画一完成后才运行动画二?

转载 作者:行者123 更新时间:2023-12-02 22:37:23 24 4
gpt4 key购买 nike

我知道这个问题已经得到解答,但大多数都是在 jquery 中。目前功能一和功能二同时运行。但是我如何更改此代码,以便功能二仅在功能一完成其到达屏幕顶部并再次返回的旅程后运行?

<html>
<head>
<title>JavaScript Animation</title>
</head>
<body>
<script>
function start() {
animation();
animationone();
}
function animation() {
obj = document.getElementById("jbtext");
obj.style.position = "absolute";
obj.style.bottom = "0px";
w = document.body.clientHeight;
goUp = true;
animateText();
}
var obj, w, goUp;
function animateText() {
var pos = parseInt(obj.style.bottom, 10);
(goUp) ? pos++ : pos--;
obj.style.bottom = pos + "px";
if (pos < 0) {
goUp = true;
}
if (pos > w) {
goUp = false;
}
if (pos < 0) {
return;
}
setTimeout(animateText, 10);
}
document.addEventListener("DOMContentLoaded", start, false);
function animationone() {
obja = document.getElementById("jbtexta");
obja.style.position = "absolute";
obja.style.left = "10px";
obja.style.bottom = "10px";
wtwo = document.body.clientWidth;
goRight = true;
animatesecond();
}
var obja, wtwo, goRight;
function animatesecond() {
var position = parseInt(obja.style.left, 10);
(goRight) ? position++ : position--;
obja.style.left = position + "px";
if (position > wtwo) {
goRight = false;
}
if (position < 0) {
goRight = true;
}
if (position < 0) {
return;
}
setTimeout(animatesecond, 10);
}
</script>
<p id="jbtext"> first function</p>
<p id="jbtexta"> second function</p>
</body>
</html>

最佳答案

您可以在 JavaScript 中使用 Promise。 Promise 是一段代码,它将异步运行并在稍后的时间点返回。它通过调用作为 Promise 构造函数的参数的解析方法来“返回”。然后,您可以将 Promise 链接在一起来完成您需要的任务。

function animationOne() {
return new Promise(function(resolve) {
// ... do your logic for the first animation here here.

resolve(); // <-- call this when your animation is finished.
})
}

function animationTwo() {
return new Promise(function(resolve) {
// ... do your logic for animation two here.

resolve(); // <-- call this when your animation is finished.
})
}

animationOne().then(function() {
animationTwo();
})

关于javascript - 如何仅在动画一完成后才运行动画二?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701074/

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