- 实现思路:
- 使用 CSS 定义好包含多个属性过渡且不同时间函数的动画样式。
- 在 JavaScript 中,通过
addEventListener
监听特定事件。当事件触发时,为目标元素添加相应的 CSS 类来启动动画。
- 利用
transitionend
事件来监听动画结束,在动画结束的回调函数中执行特定的操作。
- 关键代码片段:
/* 定义动画样式 */
.element {
position: relative;
width: 100px;
height: 100px;
background - color: red;
transition - property: left, width, background - color;
transition - duration: 1s, 2s, 3s;
transition - timing - function: ease - in - out, linear, ease - out;
}
/* 动画启动后的样式 */
.element.animate {
left: 200px;
width: 200px;
background - color: blue;
}
// 获取目标元素
const element = document.querySelector('.element');
// 监听特定事件(这里假设是点击事件)
element.addEventListener('click', () => {
// 添加动画类以启动动画
element.classList.add('animate');
// 监听动画结束
element.addEventListener('transitionend', function handleTransitionEnd() {
// 移除动画结束的监听器,避免多次触发
element.removeEventListener('transitionend', handleTransitionEnd);
// 执行特定的回调函数
console.log('动画结束,执行特定操作');
});
});