JQuery:只有在完成大小调整后才能调用RESIZE事件?

nic*_*ckb 109 html javascript jquery

一旦浏览器窗口完成大小调整,如何调用函数?

我试图这样做,但我遇到了问题.我正在使用JQuery Resize事件函数:

$(window).resize(function() {
  ... // how to call only once the browser has FINISHED resizing?
});
Run Code Online (Sandbox Code Playgroud)

但是,如果用户手动调整浏览器窗口的大小,则会连续调用此函数.这意味着,它可能会在短时间内调用此函数数十次.

我怎么只能拨打调整大小功能单一的时间(一旦浏览器窗口已经完成调整)?

UPDATE

也无需使用全局变量.

Zev*_*van 129

以下是使用jh指令的示例

您可以将引用ID存储到任何setInterval或setTimeout.像这样:

var loop = setInterval(func, 30);

// some time later clear the interval
clearInterval(loop);
Run Code Online (Sandbox Code Playgroud)

  • 我想你错过了帖子末尾的链接......看看吧:http://jsfiddle.net/Zevan/c9UE5/5/ (4认同)

BGe*_*sen 85

辩论.

function debouncer( func , timeout ) {
   var timeoutID , timeout = timeout || 200;
   return function () {
      var scope = this , args = arguments;
      clearTimeout( timeoutID );
      timeoutID = setTimeout( function () {
          func.apply( scope , Array.prototype.slice.call( args ) );
      } , timeout );
   }
}


$( window ).resize( debouncer( function ( e ) {
    // do stuff 
} ) );
Run Code Online (Sandbox Code Playgroud)

注意,您可以将此方法用于任何您想要去抖的事件(关键事件等).

调整超时参数以获得最佳效果.

  • 这是一个可重用的抽象,因此您不必手动编写超时或自己跟踪全局超时ID.你可以使用它更多,然后只是窗口大小调整;)例如通过传递更高的超时参数去抖动提交按钮.您可以选择较少的代码解决方案,但我建议您将此代码段保存在您的工具包中,稍后您将会欣赏它;) (4认同)
  • @ user43493:它调用cuntion`func`,内部`this`指针指向`scope`,并调用`Array.prototype.slice.call(args)`(从`args`生成一个标准数组)作为论点 (3认同)
  • 如果你已经在使用那个lib,Underscore.js有一个很好的实现.http://underscorejs.org/#debounce (2认同)

yck*_*art 22

您可以使用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));
});
Run Code Online (Sandbox Code Playgroud)

更新

我写了一个扩展来增强jQuery的默认on(&bind)-event-handler.如果在给定间隔内未触发事件,它会将一个或多个事件的事件处理函数附加到所选元素.如果您只想在延迟之后触发回调(例如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));
Run Code Online (Sandbox Code Playgroud)

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

$(window).on('resize', function(e) {
    console.log(e.type + '-event was 200ms not triggered');
}, 200);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/ARTsinn/EqqHx/


小智 7

var lightbox_resize = false;
$(window).resize(function() {
    console.log(true);
    if (lightbox_resize)
        clearTimeout(lightbox_resize);
    lightbox_resize = setTimeout(function() {
        console.log('resize');
    }, 500);
});
Run Code Online (Sandbox Code Playgroud)


kof*_*fus 7

只是为了添加上面的内容,通常会因为滚动条的弹出和弹出而获得不需要的调整大小事件,这里有一些代码可以避免这种情况:

function registerResize(f) {
    $(window).resize(function() {
        clearTimeout(this.resizeTimeout);
        this.resizeTimeout = setTimeout(function() {
            var oldOverflow = document.body.style.overflow;
            document.body.style.overflow = "hidden";
            var currHeight = $(window).height(),
                currWidth = $(window).width();
            document.body.style.overflow = oldOverflow;

            var prevUndefined = (typeof this.prevHeight === 'undefined' || typeof this.prevWidth === 'undefined');
            if (prevUndefined || this.prevHeight !== currHeight || this.prevWidth !== currWidth) {
                //console.log('Window size ' + (prevUndefined ? '' : this.prevHeight + "," + this.prevWidth) + " -> " + currHeight + "," + currWidth);
                this.prevHeight = currHeight;
                this.prevWidth = currWidth;

                f(currHeight, currWidth);
            }
        }, 200);
    });
    $(window).resize(); // initialize
}

registerResize(function(height, width) {
    // this will be called only once per resize regardless of scrollbars changes
});
Run Code Online (Sandbox Code Playgroud)

jsfiddle


tyb*_*103 5

Underscore.js有几个很好的方法来完成这项任务:throttledebounce.即使您没有使用下划线,也请查看这些功能的来源.这是一个例子:

var redraw = function() {'redraw logic here'};
var debouncedRedraw = _.debounce(redraw, 750);
$(window).on('resize', debouncedRedraw);
Run Code Online (Sandbox Code Playgroud)