我的 JavaScript 在决定是否等待 animationend
时遇到了一些问题事件与否,想知道是否存在解决此问题的优雅解决方案。
假设我有一个 div 在页面加载时设置动画并淡入,然后稍后我有另一个附加 <img>
的脚本标记到 div。
我想要 <img>
在动画完成之后附加,以避免动画期间出现任何卡顿并使其看起来更漂亮。
目前我知道我可以写这样的东西(假设我使用 animate.css):
HTML:
<div class="append-image-here animated fadeIn"></div>
JavaScript:
$(function() {
$('.append-image-here').one([
'webkitAnimationEnd',
'mozAnimationEnd',
'MSAnimationEnd',
'oanimationend',
'animationend'
].join(' '), function() {
$('<img>', { src: '/image.jpg' }).appendTo(this);
});
});
如果脚本在动画完成之前运行并且 animationend
就可以了事件触发,但如果脚本恰好在动画结束后运行 <img>
标签将永远不会被创建,也永远不会被附加到 div(例如,如果处理程序被设置为超时或类似超过动画持续时间的东西)。
有什么方法可以检测 CSS 动画当前是否正在运行,以便脚本可以决定是否等待 animationend
或者不需要依赖用户添加的类或数据属性?
(我要求不要依赖类和属性,因为如果我正在处理其他人的动画,我可能无法提前知道这些类)
如有任何帮助,我们将不胜感激。
最佳答案
为什么不在文档上使用 .on()
甚至检查哪个动画刚刚
已完成以及哪个元素已设置动画(e.target
)事件处理程序将在 DOM 完全加载并触发 CSS 动画之前附加。
注意:DOM 就绪时不要附加 - $(function(){ ... })
$(document).on([
'webkitAnimationEnd',
'mozAnimationEnd',
'MSAnimationEnd',
'oanimationend',
'animationend'
].join(' '), function(e) {
//Do whatever you want
console.log(e);
$('ul').append(
"<li>Animation end detected on: "
+ e.target
+ "." + e.target.className +
"</li>"
);
});
$(function(){
$('button').click(function(){
$(this).addClass('animate');
});
});
$(document).on([
'webkitAnimationEnd',
'mozAnimationEnd',
'MSAnimationEnd',
'oanimationend',
'animationend'
].join(' '), function(e) {
//Do whatever you want
console.log(e);
$('ul').append(
"<li>Animation end detected on: "
+ e.target
+ "." + e.target.className +
"</li>"
);
$('button').removeClass('animate');
});
button {
width: 300px;
background-color: red;
}
button.animate {
-webkit-animation-name: example; /* Chrome, Safari, Opera */
-webkit-animation-duration: 1s; /* Chrome, Safari, Opera */
animation-name: example;
animation-duration: 1s;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
/* Standard syntax */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="animate">Trigger animation</button>
<ul></ul>
关于JavaScript 检测正在进行的 CSS 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31112901/