火灾调整事件一次不基于时间

Fire resize event once not based on timing

本文关键字:于时间 时间 一次 调整 火灾 事件      更新时间:2023-09-26

是否有可能避免浏览器两次触发事件,但不基于时间(如果您的resize事件执行时间很长,解决方案是坏的)

window.blockResize = false;
$(window).resize(function() {
    if (window.blockResize) return;
        //do stuff

    window.blockResize = true;
    setTimeout(function(){window.blockResize = false},200);

});

好的,它仍然是基于计时器,但它现在在我的情况下工作。

您可以将setTimeout()clearTimeout()jQuery.data结合使用:

$(window).resize(function() {
    clearTimeout($.data(this, 'resizeTimer'));
    $.data(this, 'resizeTimer', setTimeout(function() {
        //do something
        alert("Haven't resized in 200ms!");
    }, 200));
});

我写了一个扩展来增强jQuery的默认on (&bind)事件处理程序。如果在给定的时间间隔内没有触发事件,则将一个或多个事件的事件处理程序函数附加到所选元素。如果您希望仅在延迟之后(如resize事件)触发回调,或者其他情况下,这很有用。https://github.com/yckart/jquery.unevent.js
;(function ($) {
    var methods = { on: $.fn.on, bind: $.fn.bind };
    $.each(methods, function(k){
        $.fn[k] = function () {
            var args = [].slice.call(arguments),
                delay = args.pop(),
                fn = args.pop(),
                timer;
            args.push(function () {
                var self = this,
                    arg = arguments;
                clearTimeout(timer);
                timer = setTimeout(function(){
                    fn.apply(self, [].slice.call(arg));
                }, delay);
            });
            return methods[k].apply(this, isNaN(delay) ? arguments : args);
        };
    });
}(jQuery));

像其他onbind事件处理程序一样使用它,除了可以传递一个额外的参数作为最后一个:

$(window).on('resize', function(e) {
    console.log(e.type + '-event was 200ms not triggered');
}, 200);
http://jsfiddle.net/ARTsinn/EqqHx/