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

后端 未结 24 1608
深忆病人
深忆病人 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:18

    this worked for me as I did not want to use any plugins.

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

    On window re-size invoke "setFn" which gets width of window and save as "originalWindowSize". Then invoke "checkFn" which after 500ms (or your preference) gets the current window size, and compares the original to the current, if they are not the same, then the window is still being re-sized. Don't forget to remove console messages in production, and (optional) can make "setFn" self executing.

提交回复
热议问题