如何防止用户拖动滚动条移动页面



我不想删除滚动条。我希望它在那里指示还有更多要滚动的内容,但即使他们拖动滚动条,我也想阻止页面表单移动(直到发生特定事件)。我该怎么做?

这不起作用:

/* This does NOT stop the page form moving when the drag the scrollbar */
document.addEventListener( "scroll", function(event) {
     console.log( "scrolled");
     event.preventDefault(); 
     event.stopPropagation();
     return false;
  },
  false
);

https://jsfiddle.net/4atyw01h/

刚刚发现了一个可能的答案(它有效):除了防止默认传播之外,您还需要将元素的scrollTop设置为 0(或您想要锁定它的任何位置):

document.addEventListener( "scroll", function(event) {
     console.log( "scrolled");
     event.preventDefault(); 
     event.stopPropagation();
     //This stops it
     document.body.scrollTop = 0;
     return false;
  },
  false
);

https://jsfiddle.net/4atyw01h/1/

无需调用 event.preventDefault()event.stopPropagation() 方法。document.body.scrollTop = 0作业就足够了。调用window.scrollTo(0, 0)以防止滚动整个文档。我在Chrome中进行了测试。

最新更新