關於window的resize事件


也許你也遇到過這樣的問題,或者還沒注意到有過這樣的問題,如下代碼,在窗口發生變化時,會進入死循環:

var _funResize = function(){
    console.log('resize...' + Math.random());
}
$(window).bind('resize',_funResize);

是問題,總得研究解決,方案:

var _funResize = function(){
    // 先解除綁定
    $(window).unbind('resize',_funResize);
   
    console.log('resize...' + Math.random());
   
    // 重新綁定
    setTimeout(function(){
        $(window).bind('resize',_funResize);
    },10);
}
$(window).bind('resize',_funResize);

但是這種方法只能是觸發第一次resize事件,有時我們是想觸發最后一次resize事件。可以通過時間來判斷

        var rtime = new Date();
        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($(window).height());
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM