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

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


当前回答

我发现改变身体的风格是没有必要的。

我们唯一需要做的就是防止整个文档(html元素)出现y滚动。

我们可以用Javascript来创建和销毁样式表。我是这样做的:

https://jsfiddle.net/3os72ryk/

var scroll_style_element;

function disable_scrolling(){
    
  // Create a style sheet we will only use to disable scrolling :
  scroll_style_element = document.createElement('style');
  document.head.appendChild(scroll_style_element);
  const scroll_style_sheet = scroll_style_element.sheet;
    
  scroll_style_sheet.insertRule('html{height:100%;overflow-y:hidden;}', scroll_style_sheet.cssRules.length);
}

function enable_scrolling(){
  if( scroll_style_element ) document.head.removeChild(scroll_style_element);
}

非常有兴趣知道是否有人发现这种方法有问题,所以如果你发现了,请在下面评论。

其他回答

只需在body中添加一个类即可:

.stop-scrolling {
  height: 100%;
  overflow: hidden;
}

添加类,然后删除当你想重新启用滚动,测试在IE, FF, Safari和Chrome。

$('body').addClass('stop-scrolling')

对于移动设备,你需要处理touchmove事件:

$('body').bind('touchmove', function(e){e.preventDefault()})

并取消绑定以重新启用滚动。在iOS6和Android 2.3.3测试

$('body').unbind('touchmove')

this.style.overflowX = 'hidden'; 您可以在函数中使用此代码行,并在被单击的特定元素上工作。

我在触摸设备上也有类似的问题。向元素添加“touch-action: none”解决了这个问题。

获取更多信息。看看这个:-

https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action

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

对于这个问题,仍然有许多变通办法来显示滚动条,比如给容器一个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和其他现代浏览器中,你必须在addEventListener调用中添加passive:false来使preventDefault生效。所以我用这个来停止手机上的滚动:

function preventDefault(e){
    e.preventDefault();
}

function disableScroll(){
    document.body.addEventListener('touchmove', preventDefault, { passive: false });
}
function enableScroll(){
    document.body.removeEventListener('touchmove', preventDefault, { passive: false });
}