与发布的答案相反,我不鼓励使用window.setTimeout,因为它不能保证计时器与动画结束事件同步,这些事件有时会被卸载到 GPU。如果你想更加确定,你应该听animationend event,并在回调本身中解决它,即:
let move_box_one = () => {
return new Promise((resolve, reject) => {
const el = document.getElementById('div_one');
const onAnimationEndCb = () => {
el.removeEventListener('animationend', onAnimationEndCb);
resolve();
}
el.addEventListener('animationend', onAnimationEndCb)
el.style.animation = 'move 3s forwards';
});
}
更好的是,由于您为两个盒子编写了一些重复的逻辑,您可以将所有这些抽象为一个返回承诺的通用函数:
// We can declare a generic helper method for one-time animationend listening
let onceAnimationEnd = (el, animation) => {
return new Promise(resolve => {
const onAnimationEndCb = () => {
el.removeEventListener('animationend', onAnimationEndCb);
resolve();
}
el.addEventListener('animationend', onAnimationEndCb)
el.style.animation = animation;
});
}
let move_box_one = async () => {
const el = document.getElementById('div_one');
await onceAnimationEnd(el, 'move 3s forwards');
}
let move_box_two = async () => {
const el = document.getElementById('div_two');
await onceAnimationEnd(el, 'move 3s forwards');
}
另外,您的 move_boxes 函数有点复杂。如果您想异步运行单个盒子移动动画,请将其声明为异步方法并简单地等待单个盒子移动函数调用,即:
let move_boxes = async () => {
await move_box_one();
await move_box_two();
}
move_boxes().then(() => console.log('boxes moved'));
查看概念验证示例(或者您可以从原始示例中的 this JSFiddle that I've forked 查看它):
// We can declare a generic helper method for one-time animationend listening
let onceAnimationEnd = (el, animation) => {
return new Promise(resolve => {
const onAnimationEndCb = () => {
el.removeEventListener('animationend', onAnimationEndCb);
resolve();
}
el.addEventListener('animationend', onAnimationEndCb)
el.style.animation = animation;
});
}
let move_box_one = async () => {
const el = document.getElementById('div_one');
await onceAnimationEnd(el, 'move 3s forwards');
}
let move_box_two = async () => {
const el = document.getElementById('div_two');
await onceAnimationEnd(el, 'move 3s forwards');
}
let move_boxes = async () => {
await move_box_one();
await move_box_two();
}
move_boxes().then(() => console.log('boxes moved'));
#div_one {
width: 50px;
height: 50px;
border: 10px solid red;
}
#div_two {
width: 50px;
height: 50px;
border: 10px solid blue;
}
@keyframes move {
100% {
transform: translateX(300px);
}
}
@keyframes down {
100% {
transform: translateY(300px);
}
}
<div id="div_one"></div>
<div id="div_two"></div>