所以我目前使用的是:

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

但是在调整大小过程中,这个函数会被调用很多次。是否有可能在事件结束时捕获事件?


当前回答

因为选择的答案实际上没有工作。如果你没有使用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();
}

其他回答

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

这里还有其他很好的答案,展示了如何使用setTimeout和lodash和下划线中的.throttle, .debounce方法,所以我将提到Ben Alman的throttle-debounce jQuery插件,它实现了你想要的东西。

假设你有这样一个函数,你想在调整大小后触发:

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

节流阀的例子 在下面的例子中,onResize()在调整窗口大小的过程中只会每250毫秒调用一次。

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

防反跳的例子 在下面的例子中,onResize()只会在窗口调整动作结束时被调用一次。这与@Mark在他的回答中呈现的结果相同。

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

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

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

我写了一个函数,当包装在任何调整大小事件时传递一个函数。它使用一个间隔,这样调整大小甚至不会不断地创建超时事件。这允许它独立于调整大小事件(而不是应该在生产中删除的日志项)执行。

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

            }

}

下面是一个非常简单的脚本,可以在窗口对象上触发'resizestart'和'resizeend'事件。

没有必要在日期和时间上浪费时间。

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

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

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

resizeend: 美元(窗口)。on('resizeend', function(event){console.log(' resizeend !');});

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

更新!

我还创造了一个更好的选择: 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!
*/