简体   繁体   中英

(Jquery/Javascript) Event Handle - Lose Focus

here's my question, i'm developing a personal website that has a huge animation in the background, with clouds moving around in an infinite loop. Everything is done with jquery extended with jquery timers and sprites. | First it fills out the cloud starting position matrix (random) | it set's the actual position of each cloud. | start moving the clouds with .animate() function and start a timer to fire again that animation until the clouds reach the left border. | repeat forever :)

Anyway this method consume a "little" memory and CPU, i'm trying to optimize the code, and i was wondering if there's a method to call a function when the browser switch to a different page , to stop the animation.

Thanks.

Plus, if anyone would help in optimizing code, i will appreciate so much! :) I'll post the link to the website if anyone could help with that. Thanks Again

屏幕截图

First, make sure you animate a single DOM-element, not a bunch of individual clouds. Put your clouds into a container and move the latter.

Second, take a look at CSS3 transitions . They are much smoother (GPU-accelerated), than JavaScript-based animation. Also, super-easy to learn and use. Just describe a CSS class and add it to your clouds upon initial position setting.

As for the determining if the browser tab is in the background, requestAnimationFrame , used by jQuery as animation ticker which is a 60 FPS ticker, can do that for you automatically .


It appears, jQuery is no longer using requestAnimationFrame (they used to at some point, but then removed it). So, here's an animate function employing requestAnimationFrame (with a setTimeout shim for IE) you can steal ideas from (or just grab the function itself).

You could listen to the window's blur and focus events:

$(window).on('blur', function() {
    // window went into background, stop animations here
    // ...
});

$(window).on('focus', function() {
    // window became active, start animations here
    // ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM