Prevent Scroll Script
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = [37, 38, 39, 40];
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function keydown(e) {
for (var i = keys.length; i--;) {
if (e.keyCode === keys[i]) {
preventDefault(e);
return;
}
}
}
function wheel(e) {
preventDefault(e);
}
function disable_scroll() {
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = wheel;
document.onkeydown = keydown;
}
function enable_scroll() {
if (window.removeEventListener) {
window.removeEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = document.onkeydown = null;
}
Usage
Call disable_scroll(); to disable the page scrolling and enable_scroll() to enable the scrolling once again.
The Problem
Unlike the Facebook modal box, you are still able to click and drag the page to scroll down.
JSFiddle
解决方案
@Terry's first sentence provides a quick solution. Simply change overflow to 'hidden' on the body to prevent scrolling.
You will also need to keep track of the window's scrolled position, and set it after changing the overflow property.
To prevent the mousewheel from being able to drag, attach a scroll event to the window, which sets scrollTop to the window's position when the modal dialog was opened:
function disable_scroll() {
var top= $(window).scrollTop();
$('body').css({
overflow: 'hidden'
});
$(window).scrollTop(top);
$(window).on('scroll', function() {
$(window).scrollTop(top);
});
}
function enable_scroll() {
var top= $(window).scrollTop();
$('body').css({
overflow: ''
});
$(window).scrollTop(top);
$(window).off('scroll');
}
Because modal_close and modal_2 in your code has href="#", the script will attempt to jump to the top of the page. You can prevent that using preventDefault:
$('a[href=#]').on('click', function(ev) {
ev.preventDefault();
});