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);
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);
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
我在网上找到这段代码,它会在所有浏览器中锁定你的滚动条,我只想锁定某些滚动条,但这段代码锁定了所有滚动条。 我只想锁定背景滚动条,我不想使用 css。
但正如您在演示中看到的那样,两个滚动条都不会移动。
最佳答案
Javascript 解决方案
如果您真的想为此使用 Javascript 并仅在用户位于特定的 div
或元素上时锁定滚轮(这就是您正在做的),您可以通过添加这些元素的悬停监听器:
$('#lock').hover(function() {
disableScroll();
}, function() {
enableScroll();
});
检查我的 jsFiddle 以获得工作演示: http://jsfiddle.net/DHz77/553/
CSS 解决方案
如果您想禁用滚动条并使用 css 规则在特定的 div 上滚动,请使用:
#lock { /* or .classname */
height: 100%; /* or some px */
overflow-y:hidden;
}
在你的情况下,它实际上是滚动的 body ,所以我也必须调整 body 的 css:
关于javascript - 在某些部分锁定滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33734115/