我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)

当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。


当前回答

还有另一个解决方案!

而不是使用多个事件监听器和添加,停止和关闭它们,你可以只添加一次回调监听器,其中你可以在你的函数中共享事件,只在需要的时候调用preventDefault等等,甚至实现自己的事件优先级系统。

其他回答

在Chrome 56和其他现代浏览器中,你必须在addEventListener调用中添加passive:false来使preventDefault生效。所以我用这个来停止手机上的滚动:

function preventDefault(e){
    e.preventDefault();
}

function disableScroll(){
    document.body.addEventListener('touchmove', preventDefault, { passive: false });
}
function enableScroll(){
    document.body.removeEventListener('touchmove', preventDefault, { passive: false });
}

Galambalazs的解决方案很棒!它在Chrome和Firefox中都非常适合我。它还可以扩展,以防止来自浏览器窗口的任何默认事件。 假设你在画布上做一个应用。你可以这样做:

var events = {
  preventDefault: function(e) {
    e = e || window.event;
    if (e.preventDefault) e.preventDefault();
    e.returnValue = false;  
  },

  //spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36,
  //left: 37, up: 38, right: 39, down: 40
  keys: [32, 33, 34, 35, 36, 37, 38, 39, 40],
  keydown: function(e) {
    for (var i = events.keys.length; i--;) {
      if (e.keyCode === events.keys[i]) {
        events.preventDefault(e);
        return;
      }
    }
  },

  wheel: function(e) {
    events.preventDefault(e);
  },

  disable: function() {
    if (window.addEventListener) {
      window.addEventListener('DOMMouseScroll', events.wheel, false);
    }
    window.onmousewheel = document.onmousewheel = events.wheel;
    document.onkeydown = helpers.events.keydown;
  },

  enable: function() {
    if (window.removeEventListener) {
      window.removeEventListener('DOMMouseScroll', events.wheel, false);
    }
    window.onmousewheel = document.onmousewheel = document.onkeydown = null;  
  }
}

然后在你的应用程序中,假设你要处理你自己的事件,比如鼠标、键盘、触摸事件等等。你可以在鼠标进入画布时禁用默认事件,并在鼠标离开时重新启用它们:

function setMouseEvents(canvas) {
  var useCapture = false;

  //Mouse enter event
  canvas.addEventListener('mouseenter', function(event) {
    events.disable();
  }, useCapture);

  //Mouse leave event
  canvas.addEventListener('mouseleave', function(event) {
    events.enable();
  }, useCapture);
}

你甚至可以禁用右键菜单与此hack:

function disableRightClickMenu(canvas) {
  var my_gradient = canvas.context.createLinearGradient(0, 0, 0, 225);
  my_gradient.addColorStop(0, "white");
  my_gradient.addColorStop(1, "white");
  canvas.context.fillStyle = my_gradient;
  canvas.context.fillRect(0, 0, canvas.width, canvas.height);
  canvas.oncontextmenu = function() { return false; };
}

我刚刚整理的一些东西:

斯菲德尔

document.onwheel = function(e) { // get the target element target = e.target; // the target element might be the children of the scrollable element // e.g., "li"s inside an "ul", "p"s inside a "div" etc. // we need to get the parent element and check if it is scrollable // if the parent isn't scrollable, we move up to the next parent while (target.scrollHeight <= target.clientHeight) { // while looping parents, we'll eventually reach document.body // since body doesn't have a parent, we need to exit the while loop if (target == document.body) { break; } target = target.parentElement; } // we want this behaviour on elements other than the body if (target != document.body) { // if the scrollbar is at the top and yet if it still tries to scroll up // we prevent the scrolling if (target.scrollTop <= 0 && e.deltaY < 0) { e.preventDefault(); } // similarly, if the scrollbar is at the bottom and it still tries to scroll down // we prevent it else if (target.clientHeight + target.scrollTop >= target.scrollHeight && e.deltaY > 0) { e.preventDefault(); } } }; body { background: gainsboro; } #box { width: 300px; height: 600px; padding: 5px; border: 1px solid silver; margin: 50px auto; background: white; overflow: auto; } <div id="box"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </div>

根据galambalazs的帖子,我将添加对触摸设备的支持,允许我们触摸但不能上下滚动:

function disable_scroll() {
   ...
   document.ontouchmove = function(e){ 
        e.preventDefault(); 
   }
}

function enable_scroll() {
   ...
   document.ontouchmove = function(e){ 
     return true; 
   }
}

这是目前为止我得到的最简单的解。相信我,其他的我都试过了,这是最简单的。它在Windows设备上工作得很好,它将页面从右边推到为系统滚动条留出空间,而IOS设备在浏览器中不需要滚动条的空间。所以通过使用这个,你不需要在右边添加填充,所以当你隐藏溢出的正文或html与css页面不会闪烁。

如果你仔细想想,解决方法其实很简单。其思想是在弹出窗口被打开时赋予window.scrollTop()相同的确切位置。当窗口调整大小时也要改变这个位置(因为一旦发生这种情况,滚动位置就会改变)。

所以我们开始…

首先,让我们创建一个变量,让你知道弹出窗口是打开的,并将其称为stopWindowScroll。如果我们不这样做,那么你会在你的页面上得到一个未定义变量的错误,并将其设置为0 -不活跃。

$(document).ready(function(){
    stopWindowScroll = 0;
});

现在让我们创建一个打开的弹出函数witch可以是你代码中的任何函数,它可以触发你作为插件或自定义使用的任何弹出。在这种情况下,它将是一个简单的自定义弹出窗口,带有一个简单的文档点击功能。

$(document).on('click','.open-popup', function(){
    // Saving the scroll position once opening the popup.
    stopWindowScrollPosition = $(window).scrollTop();
    // Setting the stopWindowScroll to 1 to know the popup is open.
    stopWindowScroll = 1;
    // Displaying your popup.
    $('.your-popup').fadeIn(300);
});

接下来我们要做的就是创建close popup函数,我再重复一遍,这个函数可以是你已经创建的或者在插件中使用的任何函数。重要的是,我们需要这两个函数来设置stopWindowScroll变量为1或0,以知道它何时打开或关闭。

$(document).on('click','.open-popup', function(){
    // Setting the stopWindowScroll to 0 to know the popup is closed.
    stopWindowScroll = 0;
    // Hiding your popup
    $('.your-popup').fadeOut(300);
});

然后让我们创建窗口。scroll函数,这样我们可以防止滚动一旦上面提到的stopWindowScroll设置为1 -作为活动。

$(window).scroll(function(){
    if(stopWindowScroll == 1) {
         // Giving the window scrollTop() function the position on which
         // the popup was opened, this way it will stay in its place.
         $(window).scrollTop(stopWindowScrollPosition);
    }
});

这是它。除了您自己的页面样式外,不需要CSS来完成此工作。这对我来说很有吸引力,我希望它能帮助到你和其他人。

下面是JSFiddle的一个工作示例:

JS小提琴示例

如果有帮助,请告诉我。的问候。