防止页面滚动-禁用拖动 [英] Preventing Page Scroll - Disabling Drag

查看:440
本文介绍了防止页面滚动-禁用拖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// 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_closemodal_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();
});

小提琴

这篇关于防止页面滚动-禁用拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆