How to wait for the 'end' of 'resize' event and only then perform an action?

后端 未结 24 1455
深忆病人
深忆病人 2020-11-22 09:39

So I currently use something like:

$(window).resize(function(){resizedw();});

But this gets called many times while resizing process goes o

24条回答
  •  独厮守ぢ
    2020-11-22 10:19

    Here is VERY simple script to trigger both a 'resizestart' and 'resizeend' event on the window object.

    There is no need to muck around with dates and times.

    The d variable represents the number of milliseconds between resize events before triggering the resize end event, you can play with this to change how sensitive the end event is.

    To listen to these events all you need to do is:

    resizestart: $(window).on('resizestart', function(event){console.log('Resize Start!');});

    resizeend: $(window).on('resizeend', function(event){console.log('Resize End!');});

    (function ($) {
        var d = 250, t = null, e = null, h, r = false;
    
        h = function () {
            r = false;
            $(window).trigger('resizeend', e);
        };
    
        $(window).on('resize', function (event) {
            e = event || e;
            clearTimeout(t);
    
            if (!r) {
                $(window).trigger('resizestart', e);
                r = true;
            }
    
            t = setTimeout(h, d);
        });
    }(jQuery));
    

提交回复
热议问题