2016-03-16 39 views
0

如何在下面的腳本中運行「調整大小」JavaScript事件。基本上我喜歡做以下事情如果我調整窗口的大小。如何運行窗口調整大小功能?

 classie.remove(bodyEl, 'show-menu'); 
     classie.remove(bodyEl, 'noscroll'); 
     classie.remove(htmlEl, 'noscroll'); 

以下是完整的腳本:

https://jsfiddle.net/sz5rxw2a/

+0

[來源文檔】(https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onresize)。請不要在一次「調整大小」中幾次觸發此事件......我建議在此功能上設置一個標誌「beginresize」,然後再設置一個標誌以實際進行相關更改。 – Bonatti

回答

0

我可以建議你做這樣的

通過調整預設的超時值,66(MS),你可以選擇實際的事件應該多久火和執行自己的自定義功能。

(function(timeout) {  // make a local static var - timeout 

    window.addEventListener("resize", function(e) { 
    if (!timeout) { 
     timeout = setTimeout(function() { 
     timeout = null; 
     actualResizeHandler(e); 

     // Set the actual fire rate 
     }, 66); 
    } 
    }, false); 

    function actualResizeHandler(e) { 
    // handle the resize event 

    classie.remove(bodyEl, 'show-menu'); 
    classie.remove(bodyEl, 'noscroll'); 
    classie.remove(htmlEl, 'noscroll'); 

    } 

}()); 

的Src:https://developer.mozilla.org/en-US/docs/Web/Events/resize

1

其實,這是不是一個好主意,但是這將是你的代碼

window.onresize = function(){ 
    classie.remove(bodyEl, 'show-menu'); 
    classie.remove(bodyEl, 'noscroll'); 
    classie.remove(htmlEl, 'noscroll'); 
} 

編輯1

它使用debouncing function來查看是一個好主意,可以進行限制該功能多久可以啓動。我建議你使用addEventListener功能爲這些目的,具有以下配置:

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

var throttled_resize = debounce(function() { 
    classie.remove(bodyEl, 'show-menu'); 
    classie.remove(bodyEl, 'noscroll'); 
    classie.remove(htmlEl, 'noscroll'); 
}, 250); 

window.addEventListener('resize', throttled_resize); 

後者是更高性能的。快樂的編碼!