The scroll
event cannot be canceled.
(scroll
事件无法取消。)
But you can do it by canceling these interaction events: (但是您可以通过取消以下交互事件来做到这一点:)
Mouse & Touch scroll and Buttons associated with scrolling.
(鼠标 和 触摸滚动以及与滚动相关的按钮 。)
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
}
function disableScroll() {
if (window.addEventListener) // older FF
window.addEventListener('DOMMouseScroll', preventDefault, false);
document.addEventListener('wheel', preventDefault, {passive: false}); // Disable scrolling in Chrome
window.onwheel = preventDefault; // modern standard
window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
window.ontouchmove = preventDefault; // mobile
document.onkeydown = preventDefaultForScrollKeys;
}
function enableScroll() {
if (window.removeEventListener)
window.removeEventListener('DOMMouseScroll', preventDefault, false);
document.removeEventListener('wheel', preventDefault, {passive: false}); // Enable scrolling in Chrome
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
EDIT
(编辑)
Added document.addEventListener('wheel', preventDefault, {passive: false});
(添加了document.addEventListener('wheel', preventDefault, {passive: false});
)
to ensure the function still works on Chrome. (以确保该功能在Chrome上仍然有效。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…