如何运行窗口大小调整函数



如何在以下脚本中运行"调整大小"JavaScript事件。基本上,如果我调整窗口大小,我喜欢执行以下操作。

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

以下是完整的脚本:

https://jsfiddle.net/sz5rxw2a/

这实际上不是一个好主意,但这将是你的代码

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

编辑 1

最好

考虑使用去抖函数来限制函数触发的频率。我建议将 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);

后者的性能要高得多。祝您编码愉快!

我可以建议你这样做吗

通过调整预设超时值 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' );
  }
}());

来源:https://developer.mozilla.org/en-US/docs/Web/Events/resize

最新更新