When using the scrollTo jQuery plugin, it can become problematic if the user scrolls while the animation is in progress. While it's possible to disable scrolling by setting the CSS property "overflow" to "hidden," it's more desirable to keep the scrollbar visible but inactive.
To achieve this, it's necessary to prevent interaction events associated with scrolling. This includes mouse and touch scrolls, as well as buttons that trigger scrolling.
The following JavaScript code demonstrates how to disable and enable scrolling temporarily:
<br>// Prevent scroll event<br>function preventDefault(e) {<br> e.preventDefault();<br>}</p> <p>// Prevent keys associated with scrolling<br>function preventDefaultForScrollKeys(e) {<br> if (keys[e.keyCode]) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">preventDefault(e); return false;
}
}
// Dict for scroll key codes
const keys = {37: 1, 38: 1, 39: 1, 40: 1};
// Disable scrolling
function disableScroll() {
window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
window.addEventListener('wheel', preventDefault, { passive: false }); // modern desktop
window.addEventListener('touchmove', preventDefault, { passive: false }); // mobile
window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}
// Enable scrolling
function enableScroll() {
window.removeEventListener('DOMMouseScroll', preventDefault, false);
window.removeEventListener('wheel', preventDefault, { passive: false });
window.removeEventListener('touchmove', preventDefault, { passive: false });
window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}
To disable scrolling, simply call the disableScroll() function. To enable scrolling again, call the enableScroll() function.
The above is the detailed content of How Can I Temporarily Disable Scrolling in JavaScript While Maintaining Scrollbar Visibility?. For more information, please follow other related articles on the PHP Chinese website!