Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

jquery - Before after resize event

I would like to do something before and after resizing element, i have tried to bind resize event and it work:

$('#test_div').bind('resize', function(){
            // do something
});

I have found some questions, but the solutions are timeout, i don't want to use timeout. I would just like to process immediately :)

See also:

Thank for any suggestions :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no such thing as a resize end event that you can listen to. The only way to know when the user is done resizing is to wait until some short amount of time passes with no more resize events coming. That's why the solution nearly always involves using a setTimeout() because that's the best way to know when some period of time has passed with no more resize events.

This previous answer of mine listens for the .scroll() event, but it's the exact same concept as .resize(): More efficient way to handle $(window).scroll functions in jquery? and you could use the same concept for resize like this:

var resizeTimer;
$(window).resize(function () {
    if (resizeTimer) {
        clearTimeout(resizeTimer);   // clear any previous pending timer
    }
     // set new timer
    resizeTimer = setTimeout(function() {
        resizeTimer = null;
        // put your resize logic here and it will only be called when 
        // there's been a pause in resize events
    }, 500);  
}

You can experiment with the 500 value for the timer to see how you like it. The smaller the number, the more quickly it calls your resize handler, but then it may get called multiple times. The larger the number, the longer pause it has before firing, but it's less likely to fire multiple times during the same user action.

If you want to do something before a resize, then you will have to call a function on the first resize event that you get and then not call that function again during the current resize operation.

var resizeTimer;
$(window).resize(function () {
    if (resizeTimer) {
        clearTimeout(resizeTimer);   // clear any previous pending timer
    } else {
        // must be first resize event in a series
    }
     // set new timer
    resizeTimer = setTimeout(function() {
        resizeTimer = null;
        // put your resize logic here and it will only be called when 
        // there's been a pause in resize events
    }, 500);  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...