我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)

当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。


当前回答

我在这里用了一个简单的技巧:

.no-scroll{
  overflow: hidden;
}

let toggle_scrolling_state = () => {
   element.classList.toggle("no-scroll");
}

然后当你想要停止滚动事件或…

其他回答

这里有一个非常基本的方法:

window.onscroll = function () { window.scrollTo(0, 0); };

在IE6中有点不稳定。

我很抱歉回答一个旧帖子,但我正在寻找一个解决方案,遇到了这个问题。

对于这个问题,仍然有许多变通办法来显示滚动条,比如给容器一个100%的高度和一个overflow-y: scroll样式。

在我的情况下,我刚刚创建了一个div与滚动条,我显示,同时添加overflow:隐藏到主体:

function disableScroll() {
    document.getElementById('scrollbar').style.display = 'block';
    document.body.style.overflow = 'hidden';
}

元素滚动条必须具有以下样式:

overflow-y: scroll; top: 0; right: 0; display: none; height: 100%; position: fixed;

这显示了一个灰色的滚动条,希望它有助于未来的访问者。

这段代码将工作在Chrome 56和进一步(原来的答案不再工作在Chrome上)。

使用DomUtils.enableScroll()来启用滚动。

使用DomUtils.disableScroll()禁用滚动。

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

为了防止跳楼,我用了这个

export function toggleBodyScroll(disable) {
  if (!window.tempScrollTop) {
    window.tempScrollTop = window.pageYOffset; 
    // save the current position in a global variable so I can access again later

  }
  if (disable) {
    document.body.classList.add('disable-scroll');
    document.body.style.top = `-${window.tempScrollTop}px`;
  } else {
    document.body.classList.remove('disable-scroll');
    document.body.style.top = `0px`;
    window.scrollTo({top: window.tempScrollTop});
    window.tempScrollTop = 0;
  }
}

在CSS中

.disable-scroll {
  height: 100%;
  overflow: hidden;
  width: 100%;
  position: fixed;
}

CSS

  overflow-y: hidden
}

Javascript
``let body = document.querySelector('body');
if(condition)  {
 //disable scroll on the entire body
 body?.classList.add("disable-scroll");
} 
else {
 //to remove the class attrib
 body?.removeAttribute("class");
 //or to remove the disable-scroll class only
 body?.classList.remove("dissble-scroll");
}

这比长代码好多了。容易理解