网页作者禁止窗口左右拖动怎么办_防止页面滚动-禁用拖动

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();

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值