Before after resize event

前端 未结 3 2088
悲&欢浪女
悲&欢浪女 2020-12-19 20:27

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(){
         


        
3条回答
  •  天命终不由人
    2020-12-19 20:50

    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);  
    }
    

提交回复
热议问题