问题描述:

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;

}

i found this code online , which will lock your scroll bar in all browser , i only want certain scroll bar to be lock , but this code lock all scroll bar.

i only want to lock the background scroll bar and i dont wanted to use css.

but as you see in demo both scroll wont move.

Demo

网友答案:

Javascript Solution

If you want really to use Javascript for this and to lock the scroll wheel (which is what you are doing) only when a user is on a specific div or element you can do that by adding an on hover listener to these elements:

$('#lock').hover(function() {
     disableScroll();
}, function() {
     enableScroll();
});

Check my jsFiddle for a working demo: http://jsfiddle.net/DHz77/553/


CSS Solution

If you want to disable the scrollbars and scrolling on a specific div using css rules, use:

#lock { /* or .classname */
    height: 100%; /* or some px */
    overflow-y:hidden; 
}

In your case it was actually the body that was scrolling, so I had to adapt the css of the body as well:

Working demo: http://jsfiddle.net/DHz77/559/

相关阅读:
Top