Sometimes we need to do something dynamically when the browser window changes, such as adapting to the adaptive page. At this point, we need to execute the code when the window is dragged. But sometimes, the operation is more complicated, we just hope that after the window has been dragged, in the execution of code, it is very easy to cause the browser suspended animation state, this time how to solve it.
The browser window has changed
First, write the function that executes the code when the window is dragged, and the native JS can be window.onresize
used by jquery $(window).resize()
.
function () { Console.log ("The window has changed yo! ");} $ (window). Resize (function() { console.log ("Windows has changed yo! ");})
This code will be executed several times when the window is dragged, if the code is more complex, it is very easy to cause the browser to suspend animation, the page performance impact.
Resolve Resize execution multiple times
How do you implement code only after you stop the change, regardless of how the window changes? Let's make a change to the previous code:
var NULL ; $ (window). bind (function () { if (Resizetimer) cleartimeout ( Resizetimer); = SetTimeout (function() { console.log ()The window has changed yo! "); ;});
By adding timers to the code to delay execution, so that each time the window changes, we clear the event, only after he stopped, will continue to execute. Although this method can solve the problem that resize executes many times, but the feeling is not perfect.
Wresize plugin:
(function($) {$.fn.wresize=function(f) {version= ' 1.1 '; Wresize={fired:false, Width:0 }; functionresizeonce () {if($.browser.msie) {if(!wresize.fired) {wresize.fired=true; }Else{ varVersion = parseint ($.browser.version, 10); Wresize.fired=false; if(Version < 7) { return false; } Else if(Version = = 7) { //A vertical resize is fired once, an horizontal resize //twice varwidth =$ (window). width (); if(Width! =wresize.width) {wresize.width=width; return false; } } } } return true; } functionHandlewresize (e) {if(Resizeonce ()) {returnF.apply ( This, [E]); } } This. each (function() { if( This==window) { $( This). Resize (handlewresize); } Else { $( This). Resize (f); } }); return This; }; }) (JQuery);
This is to find a jquery plugin source on the Internet, you can save him as jquery.wresize.js, then reference it on your page and do the following.
function SayHello () { Console.log ("The window has changed yo! ");} $ (window). Wresize (SayHello);
Solve JavaScript in $ (window). Resize () multiple executions