How to disable scrolling temporarily?

前端 未结 30 2563
萌比男神i
萌比男神i 2020-11-21 05:16

I\'m using the scrollTo jQuery plugin and would like to know if it is somehow possible to temporarily disable scrolling on the window element through Javascript? The reason

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 05:27

    This code will work on Chrome 56 and further (original answer doesn't work on Chrome anymore).

    Use DomUtils.enableScroll() to enable scrolling.

    Use DomUtils.disableScroll() to disable scrolling.

    class DomUtils {
      // left: 37, up: 38, right: 39, down: 40,
      // spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
      static keys = { 37: 1, 38: 1, 39: 1, 40: 1 };
    
      static preventDefault(e) {
        e = e || window.event;
        if (e.preventDefault) e.preventDefault();
        e.returnValue = false;
      }
    
      static preventDefaultForScrollKeys(e) {
        if (DomUtils.keys[e.keyCode]) {
          DomUtils.preventDefault(e);
          return false;
        }
      }
    
      static disableScroll() {
        document.addEventListener('wheel', DomUtils.preventDefault, {
          passive: false,
        }); // Disable scrolling in Chrome
        document.addEventListener('keydown', DomUtils.preventDefaultForScrollKeys, {
          passive: false,
        });
      }
    
      static enableScroll() {
        document.removeEventListener('wheel', DomUtils.preventDefault, {
          passive: false,
        }); // Enable scrolling in Chrome
        document.removeEventListener(
          'keydown',
          DomUtils.preventDefaultForScrollKeys,
          {
            passive: false,
          }
        ); // Enable scrolling in Chrome
      }
    }
    

提交回复
热议问题