问题描述
// 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;
}
用法
调用disable_scroll();
禁用页面滚动,并调用enable_scroll()
再次启用滚动.
Usage
Call disable_scroll();
to disable the page scrolling and enable_scroll()
to enable the scrolling once again.
与Facebook模式框不同,您仍然可以单击并拖动页面以向下滚动.
Unlike the Facebook modal box, you are still able to click and drag the page to scroll down.
链接: http://jsfiddle.net/2rud0aLm/
推荐答案
@Terry的第一句话提供了一种快速的解决方案.只需将overflow
更改为隐藏"即可防止滚动.
@Terry's first sentence provides a quick solution. Simply change overflow
to 'hidden' on the body to prevent scrolling.
您还需要跟踪窗口的滚动位置,并在更改overflow
属性后对其进行设置.
You will also need to keep track of the window's scrolled position, and set it after changing the overflow
property.
要防止鼠标滚轮拖动,请在窗口上附加一个scroll
事件,该事件将在打开模式对话框时将scrollTop
设置为窗口的位置:
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');
}
由于代码中的modal_close
和modal_2
具有href="#"
,因此脚本将尝试跳至页面顶部.您可以使用preventDefault
来防止这种情况:
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();
});
这篇关于防止页面滚动-禁用拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!