繁体   English   中英

如何使用Java启用/禁用鼠标滚动

[英]How to Enable/Disable mouse scroll with Javascript

我一直在尝试启用/禁用JavaScript滚动,

我设法禁用了滚动,但是未能将其恢复到工作状态,

所以我试过的是:

 function noscroll() {
    window.scrollTo(0, 0);
}

我尝试使用以下代码行添加和删除滚动

 window.removeEventListener("scroll", noscroll);

 window.addEventListener("scroll", noscroll);

任何帮助深表感谢

您的方法有效,那么您的问题是什么?

 function noScroll() { window.scrollTo(0, 0) } forbid.addEventListener('click', () => { window.addEventListener('scroll', noScroll) }) allow.addEventListener('click', () => { window.removeEventListener('scroll', noScroll) }) 
 div { background-color: #f0f0f0; height: 150vh; line-height: 150vh; text-align: center; } 
 <button type="button" id="forbid">Forbid scrolling</button> <button type="button" id="allow">Allow scrolling</button> <div>scroll me</div> 

您的方法似乎起作用,如下所示:

 function noscroll() { window.scrollTo(0, 0); } document.getElementById('enable').addEventListener('click', () => { window.removeEventListener("scroll", noscroll); }); document.getElementById('disable').addEventListener('click', () => { window.addEventListener("scroll", noscroll); }); 
 div { background:pink; height:1000px; padding:50px; } header { position:fixed; top:0; left:0; z-index:1; } 
 <header> <button id="enable">Enable scrolling</button> <button id="disable">Disable scrolling</button> </header> <div> Prevent scroll via Javascript (window.scrollTo) </div> 

值得考虑的另一种方法是通过“隐藏”任何内容溢出来更新document.body元素的overflow属性。 这具有删除滚动条的副作用,这反过来又阻止了滚动:

  document.getElementById('enable').addEventListener('click', () => { // Remove overflow value from document body to restore default scrolling document.body.style.overflow = ''; }) document.getElementById('disable').addEventListener('click', () => { // When scrolling is disabled, auto scroll to top of screen window.scrollTo(0, 0); // Apply overflow:hidden to document body to prevent scrolling document.body.style.overflow = 'hidden'; }) 
 div { background:pink; height:1000px; padding:50px; } header { position:fixed; top:0; left:0; z-index:1; } 
 <header> <button id="enable">Enable scrolling</button> <button id="disable">Disable scrolling</button> </header> <div> Prevent scroll via CSS </div> 

上面显示的基于CSS的方法的主要优点是它不受“抖动”滚动行为的影响,而以前的“ pure-javascript”方法可以引起这种滚动行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM