在JavaScript中,监听CSS3动画结束可以使用animationend
事件。这个事件在CSS动画完成一个周期后触发。
基础概念:
animationend
:当CSS动画结束时触发的事件。相关优势:
应用场景:
示例代码:
HTML:
<div id="animatedElement" class="animation"></div>
CSS:
.animation {
width: 100px;
height: 100px;
background-color: red;
animation: myAnimation 2s forwards;
}
@keyframes myAnimation {
from { transform: scale(1); }
to { transform: scale(1.5); }
}
JavaScript:
const animatedElement = document.getElementById('animatedElement');
animatedElement.addEventListener('animationend', function(event) {
console.log('动画结束');
// 在这里可以执行动画结束后的操作
});
常见问题及解决方法:
animationend
事件的浏览器特定版本,如webkitAnimationEnd
、mozAnimationEnd
等。解决方法示例(考虑浏览器兼容性):
function handleAnimationEnd(event) {
console.log('动画结束');
}
const animatedElement = document.getElementById('animatedElement');
animatedElement.addEventListener('animationend', handleAnimationEnd, false);
animatedElement.addEventListener('webkitAnimationEnd', handleAnimationEnd, false); // Safari 和旧版Chrome
animatedElement.addEventListener('mozAnimationEnd', handleAnimationEnd, false); // Firefox
animatedElement.addEventListener('oanimationend', handleAnimationEnd, false); // Opera
确保在实际的项目中根据需要选择合适的浏览器兼容性处理。
领取专属 10元无门槛券
手把手带您无忧上云