Detecting if Anything on the Page is being Animated

只谈情不闲聊 提交于 2019-12-12 07:23:15

问题


I know about the :animated selector, but currently am running into (what might be one of a few) performance issue for older IE's (go figure). I feel like it might potentially be the way I'm testing for ANY Page Animation.

Currently I'm looping through an interval, with the core test being $('*').is(':animated'). This $('*') is what i'm worried about... but since I don't know exaclty what the divs / etc are that are being animated below my plugin, I'm not sure how else to do it!

var testAnimationInterval = setInterval(function () {

    if ( ! $('*').is(':animated') ) {  // all done animating
        clearInterval(testAnimationInterval);

        animationsFinished();  // callback function
    }
}, 300);

function animationsFinished() {
    // do whatever
}

Has anyone found a better / different way of doing this? Especially when it comes to performance?


回答1:


All jQuery animation timers are stored in the array $.timers. One option is just to check whether length of $.timers property is more than zero:

if ($.timers.length > 0) {
    // something is animating
}



回答2:


I think it would be more efficient to push your element to an array when the animation starts, and remove it from the array when it's done animating. Or better yet, increment a variable on animation start, and decrease it by 1, when it's done. If the variable is 0, no animation should currently be running.

So, some pseudocode:

var animatingElements = 0;

function animationStart(){ // Add this function in your animation start events;
    animatingElements++;
}

function animationEnd(){ // Add this function  in your animation end events;
    animatingElements--;
}

if (animatingElements === 0) {
    clearInterval(testAnimationInterval);
}

This is, assuming you have access to the code that starts / catches the end of your animations, of course.



来源:https://stackoverflow.com/questions/14218363/detecting-if-anything-on-the-page-is-being-animated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!