jQuery - 如何等待'resize'事件的'end'然后再执行一个动作?

时间:2011-03-30 17:37:15

标签: javascript jquery html javascript-events resize

所以我目前使用的是:

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

但是在调整大小过程的过程中会多次调用它。是否可以在事件结束时捕获事件?

24 个答案:

答案 0 :(得分:484)

您可以使用setTimeout()clearTimeout()

function resizedw(){
    // Haven't resized in 100ms!
}

var doit;
window.onresize = function(){
  clearTimeout(doit);
  doit = setTimeout(resizedw, 100);
};

jsfiddle上的代码示例。

答案 1 :(得分:161)

我很满意以下建议:http://forum.jquery.com/topic/the-resizeend-event

这是代码,因此您无需深入了解其帖子的链接&源:

var rtime;
var timeout = false;
var delta = 200;
$(window).resize(function() {
    rtime = new Date();
    if (timeout === false) {
        timeout = true;
        setTimeout(resizeend, delta);
    }
});

function resizeend() {
    if (new Date() - rtime < delta) {
        setTimeout(resizeend, delta);
    } else {
        timeout = false;
        alert('Done resizing');
    }               
}

感谢sime.vidas代码!

答案 2 :(得分:73)

这是我根据@Mark Coleman回答的代码:

$(window).resize(function() {
    clearTimeout(window.resizedFinished);
    window.resizedFinished = setTimeout(function(){
        console.log('Resized finished.');
    }, 250);
});

谢谢Mark!

答案 3 :(得分:34)

Internet Explorer提供resizeEnd个事件。在您调整大小时,其他浏览器会多次触发调整大小事件。

这里还有其他很棒的答案,展示了如何使用来自lodash和下划线的setTimeout和.throttle .debounce方法,所以我会提到本·阿尔曼的 throttle-debounce jQuery plugin 完成了你所追求的目标。

假设您在调整大小后想要触发此功能:

function onResize() {
  console.log("Resize just happened!");
};

节气门示例
在以下示例中,onResize()仅在窗口调整大小期间每250毫秒调用一次。

$(window).resize( $.throttle( 250, onResize) );

辩护示例
在以下示例中,onResize()仅在窗口大小调整操作结束时调用一次。这实现了@Mark在他的回答中提出的相同结果。

$(window).resize( $.debounce( 250, onResize) );

答案 4 :(得分:24)

使用Underscore.js有一个优雅的解决方案所以,如果您在项目中使用它,您可以执行以下操作 -

$( window ).resize( _.debounce( resizedw, 500 ) );

这应该足够:)但是,如果你有兴趣阅读更多内容,你可以查看我的博客帖子 - http://rifatnabi.com/post/detect-end-of-jquery-resize-event-using-underscore-debounce (deadlink)

答案 5 :(得分:7)

一个解决方案是使用函数扩展jQuery,例如:resized

$.fn.resized = function (callback, timeout) {
    $(this).resize(function () {
        var $this = $(this);
        if ($this.data('resizeTimeout')) {
            clearTimeout($this.data('resizeTimeout'));
        }
        $this.data('resizeTimeout', setTimeout(callback, timeout));
    });
};

样本用法:

$(window).resized(myHandler, 300);

答案 6 :(得分:7)

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

var loop = setInterval(func, 30);

// some time later clear the interval
clearInterval(loop);

要在没有“全局”变量的情况下执行此操作,您可以向函数本身添加局部变量。例如:

$(window).resize(function() {
    clearTimeout(this.id);
    this.id = setTimeout(doneResizing, 500);
});

function doneResizing(){
  $("body").append("<br/>done!");   
}

答案 7 :(得分:5)

在调整大小的末尾执行一个函数要比计算两个调用之间的增量时间要简单得多,方法很简单:

var resizeId;
$(window).resize(function() {
    clearTimeout(resizeId);
    resizeId = setTimeout(resizedEnded, 500);
});

function resizedEnded(){
    ...
}

以及 Angular2 的等效项:

private resizeId;
@HostListener('window:resize', ['$event'])
onResized(event: Event) {
  clearTimeout(this.resizeId);
  this.resizeId = setTimeout(() => {
    // Your callback method here.
  }, 500);
}

对于角度方法,请使用() => { }中的setTimeout表示法来保留范围,否则将无法进行任何函数调用或使用this

答案 8 :(得分:3)

您可以将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(&amp; 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/

答案 9 :(得分:2)

这是对上面Dolan代码的修改,我添加了一个功能,它在调整大小开始时检查窗口大小,并将其与调整大小结束时的大小进行比较,如果大小大于或小于保证金(例如1000)然后重新加载。

var rtime = new Date(1, 1, 2000, 12,00,00);
var timeout = false;
var delta = 200;
var windowsize = $window.width();
var windowsizeInitial = $window.width();

$(window).on('resize',function() {
    windowsize = $window.width();
    rtime = new Date();
    if (timeout === false) {
            timeout = true;
            setTimeout(resizeend, delta);
        }
});

function resizeend() {
if (new Date() - rtime < delta) {
    setTimeout(resizeend, delta);
    return false;
} else {
        if (windowsizeInitial > 1000 && windowsize > 1000 ) {
            setTimeout(resizeend, delta);
            return false;
        }
        if (windowsizeInitial < 1001 && windowsize < 1001 ) {
            setTimeout(resizeend, delta);
            return false;
        } else {
            timeout = false;
            location.reload();
        }
    }
    windowsizeInitial = $window.width();
    return false;
}

答案 10 :(得分:1)

(function(){
    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);

    special.resizestart = {
        setup: function() {
            var timer,
                handler =  function(evt) {
                    var _self = this,
                        _args = arguments;
                    if (timer) {
                        clearTimeout(timer);
                    } else {
                        evt.type = 'resizestart';
                        jQuery.event.handle.apply(_self, _args);
                    }

                    timer = setTimeout( function(){
                        timer = null;
                    }, special.resizestop.latency);
                };
            jQuery(this).bind('resize', handler).data(uid1, handler);
        },
        teardown: function(){
            jQuery(this).unbind( 'resize', jQuery(this).data(uid1) );
        }
    };

    special.resizestop = {
        latency: 200,
        setup: function() {
            var timer,
                handler = function(evt) {
                    var _self = this,
                        _args = arguments;
                    if (timer) {
                        clearTimeout(timer);
                    }
                    timer = setTimeout( function(){
                        timer = null;
                        evt.type = 'resizestop';
                        jQuery.event.handle.apply(_self, _args);
                    }, special.resizestop.latency);
                };

            jQuery(this).bind('resize', handler).data(uid2, handler);
        },
        teardown: function() {
            jQuery(this).unbind( 'resize', jQuery(this).data(uid2) );
        }
    };
})();

$(window).bind('resizestop',function(){
    //...
});

答案 11 :(得分:1)

我自己写了一个小小的包装函数......

onResize  =   function(fn) {
    if(!fn || typeof fn != 'function')
        return 0;

    var args    = Array.prototype.slice.call(arguments, 1);

    onResize.fnArr    = onResize.fnArr || [];
    onResize.fnArr.push([fn, args]);

    onResize.loop   = function() {
        $.each(onResize.fnArr, function(index, fnWithArgs) {
            fnWithArgs[0].apply(undefined, fnWithArgs[1]);
        });
    };

    $(window).on('resize', function(e) {
        window.clearTimeout(onResize.timeout);
        onResize.timeout    = window.setTimeout("onResize.loop();", 300);
    });
};

以下是用法:

var testFn  = function(arg1, arg2) {
    console.log('[testFn] arg1: '+arg1);
    console.log('[testFn] arg2: '+arg2);
};

// document ready
$(function() {
    onResize(testFn, 'argument1', 'argument2');
});

答案 12 :(得分:1)

这是一个非常简单的脚本,可以触发&#39; resizestart&#39;并且&#39; resizeend&#39;窗口对象上的事件。

没有必要捣乱日期和时间。

d变量表示在触发调整大小结束事件之前调整大小事件之间的毫秒数,您可以使用此变量来更改结束事件的敏感程度。

要收听这些事件,您需要做的就是:

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

答案 13 :(得分:1)

Mark Coleman的答案肯定比选择的答案要好得多,但是如果你想避免超时ID的全局变量(Mark答案中的doit变量),你可以做以下其中一项:

(1)使用一个立即调用的函数表达式(IIFE)来创建一个闭包。

$(window).resize((function() { // This function is immediately invoked
                               // and returns the closure function.
    var timeoutId;
    return function() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() {
            timeoutId = null; // You could leave this line out.
            // Code to execute on resize goes here.
        }, 100);
    };
})());

(2)使用事件处理函数的属性。

$(window).resize(function() {
    var thisFunction = arguments.callee;
    clearTimeout(thisFunction.timeoutId);
    thisFunction.timeoutId = setTimeout(function() {
        thisFunction.timeoutId = null; // You could leave this line out.
        // Code to execute on resize goes here.
    }, 100);
});

答案 14 :(得分:1)

嗯,就窗口管理器而言,每个resize事件都是它自己的消息,具有明显的开始和结束,所以从技术上讲,每次调整窗口大小时, 结束

话虽如此,也许你想延迟你的延续? Here's an example.

var t = -1;
function doResize()
{
    document.write('resize');
}
$(document).ready(function(){
    $(window).resize(function(){
        clearTimeout(t);
        t = setTimeout(doResize, 1000);
    });
});

答案 15 :(得分:0)

UPDATE!

我也创造了更好的选择: https://stackoverflow.com/a/23692008/2829600 (支持“删除功能”)

原始帖子:

我编写了这个简单的函数来处理执行中的延迟,在jQuery .scroll()和.resize()中很有用所以callback_f只对特定的id字符串运行一次。

function delay_exec( id, wait_time, callback_f ){

    // IF WAIT TIME IS NOT ENTERED IN FUNCTION CALL,
    // SET IT TO DEFAULT VALUE: 0.5 SECOND
    if( typeof wait_time === "undefined" )
        wait_time = 500;

    // CREATE GLOBAL ARRAY(IF ITS NOT ALREADY CREATED)
    // WHERE WE STORE CURRENTLY RUNNING setTimeout() FUNCTION FOR THIS ID
    if( typeof window['delay_exec'] === "undefined" )
        window['delay_exec'] = [];

    // RESET CURRENTLY RUNNING setTimeout() FUNCTION FOR THIS ID,
    // SO IN THAT WAY WE ARE SURE THAT callback_f WILL RUN ONLY ONE TIME
    // ( ON LATEST CALL ON delay_exec FUNCTION WITH SAME ID  )
    if( typeof window['delay_exec'][id] !== "undefined" )
        clearTimeout( window['delay_exec'][id] );

    // SET NEW TIMEOUT AND EXECUTE callback_f WHEN wait_time EXPIRES,
    // BUT ONLY IF THERE ISNT ANY MORE FUTURE CALLS ( IN wait_time PERIOD )
    // TO delay_exec FUNCTION WITH SAME ID AS CURRENT ONE
    window['delay_exec'][id] = setTimeout( callback_f , wait_time );
}


// USAGE

jQuery(window).resize(function() {

    delay_exec('test1', 1000, function(){
        console.log('1st call to delay "test1" successfully executed!');
    });

    delay_exec('test1', 1000, function(){
        console.log('2nd call to delay "test1" successfully executed!');
    });

    delay_exec('test1', 1000, function(){
        console.log('3rd call to delay "test1" successfully executed!');
    });

    delay_exec('test2', 1000, function(){
        console.log('1st call to delay "test2" successfully executed!');
    });

    delay_exec('test3', 1000, function(){
        console.log('1st call to delay "test3" successfully executed!');
    });

});

/* RESULT
3rd call to delay "test1" successfully executed!
1st call to delay "test2" successfully executed!
1st call to delay "test3" successfully executed!
*/

答案 16 :(得分:0)

这对我有用,因为我不想使用任何插件。

$(window).resize(function() {
    var originalWindowSize = 0;
    var currentWidth = 0;

    var setFn = function () {
        originalWindowSize = $(window).width();
    };

    var checkFn = function () {
        setTimeout(function () {
            currentWidth = $(window).width();
            if (currentWidth === originalWindowSize) {
                console.info("same? = yes") 
                // execute code 
            } else {
                console.info("same? = no"); 
                // do nothing 
            }
        }, 500)
    };
    setFn();
    checkFn();
});

在窗口重新调整大小&#34; setFn&#34;获取窗口的宽度并保存为&#34; originalWindowSize&#34;。然后调用&#34; checkFn&#34;在500ms(或您的偏好)获得当前窗口大小后,将原始值与当前值进行比较,如果它们不相同,则窗口仍在重新调整大小。不要忘记在生产中删除控制台消息,并且(可选)可以使&#34; setFn&#34;自我执行。

答案 17 :(得分:0)

var resizeTimer;
$( window ).resize(function() {
    if(resizeTimer){
        clearTimeout(resizeTimer);
    }
    resizeTimer = setTimeout(function() {
        //your code here
        resizeTimer = null;
        }, 200);
    });

这适用于我在chrome中尝试做的事情。这不会在最后一次调整大小事件后的200ms内触发回调。

答案 18 :(得分:0)

因为所选答案实际上并不起作用..如果你不使用jquery这里是一个简单的节流功能,以及如何在窗口大小调整时使用它的例子

    function throttle(end,delta) {

    var base = this;

    base.wait = false;
    base.delta = 200;
    base.end = end;

    base.trigger = function(context) {

        //only allow if we aren't waiting for another event
        if ( !base.wait ) {

            //signal we already have a resize event
            base.wait = true;

            //if we are trying to resize and we 
            setTimeout(function() {

                //call the end function
                if(base.end) base.end.call(context);

                //reset the resize trigger
                base.wait = false;
            }, base.delta);
        }
    }
};

var windowResize = new throttle(function() {console.log('throttle resize');},200);

window.onresize = function(event) {
    windowResize.trigger();
}

答案 19 :(得分:0)

窗口的

ResizeStart ResizeEnd 事件

http://jsfiddle.net/04fLy8t4/

我实现了在用户DOM元素上触发两个事件的函数:

  1. resizestart
  2. resizeend
  3. 代码:

    var resizeEventsTrigger = (function () {
        function triggerResizeStart($el) {
            $el.trigger('resizestart');
            isStart = !isStart;
        }
    
        function triggerResizeEnd($el) {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function () {
                $el.trigger('resizeend');
                isStart = !isStart;
            }, delay);
        }
    
        var isStart = true;
        var delay = 200;
        var timeoutId;
    
        return function ($el) {
            isStart ? triggerResizeStart($el) : triggerResizeEnd($el);
        };
    
    })();
    
    $("#my").on('resizestart', function () {
        console.log('resize start');
    });
    $("#my").on('resizeend', function () {
        console.log('resize end');
    });
    
    window.onresize = function () {
        resizeEventsTrigger( $("#my") );
    };
    

答案 20 :(得分:0)

var flag=true;
var timeloop;

$(window).resize(function(){
    rtime=new Date();
    if(flag){
        flag=false;
        timeloop=setInterval(function(){
            if(new Date()-rtime>100)
                myAction();
        },100);
    }
})
function myAction(){
    clearInterval(timeloop);
    flag=true;
    //any other code...
}

答案 21 :(得分:0)

我不知道我的代码是否适用于其他代码,但它对我来说真的很棒。我通过分析Dolan Antenucci代码得到了这个想法,因为他的版本不适合我,我真的希望它对某人有用。

var tranStatus = false;
$(window).resizeend(200, function(){
    $(".cat-name, .category").removeAttr("style");
    //clearTimeout(homeResize);
    $("*").one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",function(event) {
      tranStatus = true;
    });
    processResize();
});

function processResize(){
  homeResize = setInterval(function(){
    if(tranStatus===false){
        console.log("not yet");
        $("*").one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",function(event) {
            tranStatus = true;
        }); 
    }else{
        text_height();
        clearInterval(homeResize);
    }
  },200);
}

答案 22 :(得分:0)

我编写了一个函数,在包装任何resize事件时传递一个函数。它使用一个间隔,以便调整大小甚至不会不断创建超时事件。这使得它可以独立于resize事件执行,而不是应该在生产中删除的日志条目。

https://github.com/UniWrighte/resizeOnEnd/blob/master/resizeOnEnd.js

        $(window).resize(function(){
            //call to resizeEnd function to execute function on resize end.
    //can be passed as function name or anonymous function
            resizeEnd(function(){



    });

        });

        //global variables for reference outside of interval
        var interval = null;
        var width = $(window).width();
    var numi = 0; //can be removed in production
        function resizeEnd(functionCall){
            //check for null interval
            if(!interval){
                //set to new interval
                interval = setInterval(function(){
        //get width to compare
                    width2 = $(window).width();
        //if stored width equals new width
                    if(width === width2){
                        //clear interval, set to null, and call passed function
                        clearInterval(interval);
                        interval = null; //precaution
                        functionCall();

                    }
        //set width to compare on next interval after half a second
                    width = $(window).width();
                }, 500);

            }else{
                //logging that should be removed in production
                console.log("function call " + numi++ + " and inteval set skipped");

            }

}

答案 23 :(得分:0)

这是我用来延迟重复操作的方法,可以在代码中的多个位置调用它:

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

用法:

$(window).resize(function () { 
   debounce(function() {
          //...
    }, 500);
});