猿问

我可以使用 JS 等待多个 CSS 动画吗?

我们有一种方法可以使用 JS 检测动画何时结束:


const element = $('#animatable');

element.addClass('being-animated').on("animationend", (event) => {

  console.log('Animation ended!');

});

@keyframes animateOpacity {

  0% {

    opacity: 1;

  }

  100% {

    opacity: 0;

  }

}


@keyframes animatePosition {

  0% {

    transform: translate3d(0, 0, 0);

  }

  100% {

    transform: translate3d(0, 15px, 0);

  }

}


#animatable.being-animated {

  animation: animateOpacity 1s ease 0s forwards, animatePosition 2s ease 0s forwards;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="animatable">I'm probably being animated.</div>


正如你所看到的,JS,理所当然地,因为我被这个animationend事件吸引住了,它告诉我“是的,动画完成了”但不知道接下来会发生什么,我错过了第二个。


不是有动画队列吗?当然,CSS 必须在系统中的某个地方注册这些东西,然后才能在它们被触发之前达到峰值。


神不在的星期二
浏览 132回答 3
3回答

守着一只汪

免责声明:我不认为 jQuery 对回答这个问题很重要,如果其他人在看到这个答案后选择依赖此代码,它会损害负载和运行时性能。因此,我将使用 vanilla JavaScript 来回答,以帮助尽可能多的人,但如果您想使用 jQuery,您仍然可以应用相同的概念。答:没有动画队列,但您可以自己制作。例如,您可以使用闭包和/或 a Map(在下面的代码段中,我实际上使用 aWeakMap来帮助垃圾收集)将有关动画的数据链接到目标元素。如果您将动画状态保存为true完成时,您可以检查并最终在全部为 时触发不同的回调true,或者调度您自己的自定义事件。我使用了自定义事件方法,因为它更灵活(能够添加多个回调)。以下代码还可以帮助您避免在您实际上只关心几个特定动画的情况下等待所有动画。它还应该让您多次处理多个单独元素的动画事件(尝试运行代码段并单击几次框)const addAnimationEndAllEvent = (() => {&nbsp; const weakMap = new WeakMap()&nbsp; const initAnimationsObject = (element, expectedAnimations, eventName) => {&nbsp; &nbsp; const events = weakMap.get(element)&nbsp; &nbsp; const animationsCompleted = {}&nbsp; &nbsp; for (const animation of expectedAnimations) {&nbsp; &nbsp; &nbsp; animationsCompleted[animation] = false&nbsp; &nbsp; }&nbsp; &nbsp; events[eventName] = animationsCompleted&nbsp; }&nbsp; return (element, expectedAnimations, eventName = 'animationendall') => {&nbsp; &nbsp; if (!weakMap.has(element)) weakMap.set(element, {})&nbsp; &nbsp; if (expectedAnimations) {&nbsp; &nbsp; &nbsp; initAnimationsObject(element, expectedAnimations, eventName)&nbsp; &nbsp; }&nbsp; &nbsp; // When any animation completes...&nbsp; &nbsp; element.addEventListener('animationend', ({ target, animationName }) => {&nbsp; &nbsp; &nbsp; const events = weakMap.get(target)&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; // Use all animations, if there were none provided earlier&nbsp; &nbsp; &nbsp; if (!events[eventName]) {&nbsp; &nbsp; &nbsp; &nbsp; initAnimationsObject(target, window.getComputedStyle(target).animationName.split(', '), eventName)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; const animationsCompleted = events[eventName]&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; // Ensure this animation should be tracked&nbsp; &nbsp; &nbsp; if (!(animationName in animationsCompleted)) return&nbsp; &nbsp; &nbsp; // Mark the current animation as complete (true)&nbsp; &nbsp; &nbsp; animationsCompleted[animationName] = true&nbsp; &nbsp; &nbsp; // If every animation is now completed...&nbsp; &nbsp; &nbsp; if (Object.values(animationsCompleted).every(&nbsp; &nbsp; &nbsp; &nbsp; isCompleted => isCompleted === true&nbsp; &nbsp; &nbsp; )) {&nbsp; &nbsp; &nbsp; &nbsp; const animations = Object.keys(animationsCompleted)&nbsp; &nbsp; &nbsp; &nbsp; // Fire the event&nbsp; &nbsp; &nbsp; &nbsp; target.dispatchEvent(new CustomEvent(eventName, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; detail: { target, animations },&nbsp; &nbsp; &nbsp; &nbsp; }))&nbsp; &nbsp; &nbsp; &nbsp; // Reset for next time - set all animations to not complete (false)&nbsp; &nbsp; &nbsp; &nbsp; initAnimationsObject(target, animations, eventName)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; }})()const toggleAnimation = ({ target }) => {&nbsp; target.classList.toggle('being-animated')}document.querySelectorAll('.animatable').forEach(element => {&nbsp; // Wait for all animations before firing the default event "animationendall"&nbsp; addAnimationEndAllEvent(element)&nbsp; // Wait for the provided animations before firing the event "animationend2"&nbsp; addAnimationEndAllEvent(element, [&nbsp; &nbsp; 'animateOpacity',&nbsp; &nbsp; 'animatePosition'&nbsp; ], 'animationend2')&nbsp; // Listen for our added "animationendall" event&nbsp; element.addEventListener('animationendall', ({detail: { target, animations }}) => {&nbsp; &nbsp; console.log(`Animations: ${animations.join(', ')} - Complete`)&nbsp; })&nbsp; // Listen for our added "animationend2" event&nbsp; element.addEventListener('animationend2', ({detail: { target, animations }}) => {&nbsp; &nbsp; console.log(`Animations: ${animations.join(', ')} - Complete`)&nbsp; })&nbsp; // Just updated this to function on click, so we can test animation multiple times&nbsp; element.addEventListener('click', toggleAnimation)}).animatable {&nbsp; margin: 5px;&nbsp; width: 100px;&nbsp; height: 100px;&nbsp; background: black;}@keyframes animateOpacity {&nbsp; 0% {&nbsp; &nbsp; opacity: 1;&nbsp; }&nbsp; 100% {&nbsp; &nbsp; opacity: 0;&nbsp; }}@keyframes animatePosition {&nbsp; 0% {&nbsp; &nbsp; transform: translate3d(0, 0, 0);&nbsp; }&nbsp; 100% {&nbsp; &nbsp; transform: translate3d(0, 15px, 0);&nbsp; }}@keyframes animateRotation {&nbsp; 100% {&nbsp; &nbsp; transform: rotate(360deg);&nbsp; }}.animatable.being-animated {&nbsp; animation:&nbsp; &nbsp; animateOpacity 1s ease 0s forwards,&nbsp; &nbsp; animatePosition 1.5s ease 0s forwards,&nbsp; &nbsp; animateRotation 2s ease 0s forwards;}<div class="animatable"></div><div class="animatable"></div>

阿晨1998

它当然值得成为公认的答案。也就是说,我受到启发,想看看一种不那么冗长的方法是否可行。这是我想出的。这是不言自明的,但基本上概念是所有动画属性的索引都是相关的,我们可以使用它来查找最后完成的动画的名称。const getFinalAnimationName = el => {&nbsp; const style = window.getComputedStyle(el)&nbsp;&nbsp;&nbsp; // get the combined duration of all timing properties&nbsp; const [durations, iterations, delays] = ['Duration', 'IterationCount', 'Delay']&nbsp; &nbsp; .map(prop => style[`animation${prop}`].split(', ')&nbsp; &nbsp; &nbsp; .map(val => Number(val.replace(/[^0-9\.]/g, ''))))&nbsp; const combinedDurations = durations.map((duration, idx) =>&nbsp; &nbsp; duration * iterations[idx] + delays[idx])&nbsp;&nbsp;&nbsp; // use the index of the longest duration to select the animation name&nbsp; const finalAnimationIdx = combinedDurations&nbsp; &nbsp; .findIndex(d => d === Math.max(...combinedDurations))&nbsp; return style.animationName.split(', ')[finalAnimationIdx]}// pipe your element through this function to give it the ability to dispatch the 'animationendall' eventconst addAnimationEndAllEvent = el => {&nbsp; const animationendall = new CustomEvent('animationendall')&nbsp; el.addEventListener('animationend', ({animationName}) =>&nbsp; &nbsp; animationName === getFinalAnimationName(el) &&&nbsp; &nbsp; &nbsp; el.dispatchEvent(animationendall))&nbsp; return el}// example usageconst animatable = document.querySelector('.animatable')addAnimationEndAllEvent(animatable)&nbsp; .addEventListener('animationendall', () => console.log('All animations have finished')).animatable {&nbsp; width: 50px;&nbsp; height: 50px;&nbsp; background-color: red;&nbsp; position: relative;&nbsp; left: 0;&nbsp; animation: 1.5s slidein, 1s fadein;}@keyframes slidein {&nbsp; 0% { left: 100vw; }&nbsp; 100% { left: 0; }}@keyframes fadein {&nbsp; 0% { opacity: 0; }&nbsp; 100% { opacity: 1; }}<div class="animatable"></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答