按顺序执行多个动画
时间: 2023-08-29 14:07:33 浏览: 41
要按顺序执行多个动画,可以使用 JavaScript 中的 Promise 对象和 async/await 函数。以下是一个实现的示例:
```html
<!-- HTML -->
<div id="box"></div>
```
```css
/* CSS */
#box {
width: 100px;
height: 100px;
background-color: red;
}
```
```javascript
// JavaScript
const box = document.getElementById("box");
function animateBox() {
return new Promise((resolve) => {
// 第一个动画
box.style.transform = "translateX(200px)";
box.addEventListener("transitionend", () => {
resolve();
});
}).then(() => {
return new Promise((resolve) => {
// 第二个动画
box.style.transform = "rotate(90deg)";
box.addEventListener("transitionend", () => {
resolve();
});
});
}).then(() => {
// 第三个动画
box.style.backgroundColor = "blue";
});
}
async function playAnimations() {
await animateBox();
console.log("All animations completed!");
}
playAnimations();
```
在上面的代码中,`animateBox` 函数返回一个 Promise 对象,其中包含了三个动画,每个动画都是通过添加 transitionend 事件来监听其完成的。然后,`playAnimations` 函数使用 async/await 来按顺序执行这些动画。当所有动画完成时,我们会在控制台中输出一条消息。