13

我有一个可滚动的 div,但是每当您到达它的底部/顶部时,它就会开始滚动整个页面。这对于快速滚动的用户来说可能很烦人,然后整个页面开始意外滚动。

我需要一些东西,如果您将鼠标悬停在 div 上,则页面不可滚动。

当我悬停 div 时,我通过添加 CSS 来尝试过这个...

body {
    overflow:hidden;
}

...它有效,但有一个问题。滚动条消失了,让它消失/重新出现看起来有点愚蠢。有什么方法可以达到相同的效果但保持滚动条可见?我已经看到它通过 Facebook 聊天完成了。

4

2 回答 2

28

Here is a very simple way to stop the propagation with no plugins, just jQuery.

Update: The code has been updated to work correctly in IE9+. Have not tested in previous versions.

First, create a class on your <div> to mark it as having this behavior. In my example, I use the class .Scrollable.

<div class="Scrollable">
  <!-- A bunch of HTML here which will create scrolling -->
</div>

The jQuery to disable is:

$('.Scrollable').on('DOMMouseScroll mousewheel', function(ev) {
    var $this = $(this),
        scrollTop = this.scrollTop,
        scrollHeight = this.scrollHeight,
        height = $this.height(),
        delta = (ev.type == 'DOMMouseScroll' ?
            ev.originalEvent.detail * -40 :
            ev.originalEvent.wheelDelta),
        up = delta > 0;

    var prevent = function() {
        ev.stopPropagation();
        ev.preventDefault();
        ev.returnValue = false;
        return false;
    }

    if (!up && -delta > scrollHeight - height - scrollTop) {
        // Scrolling down, but this will take us past the bottom.
        $this.scrollTop(scrollHeight);
        return prevent();
    } else if (up && delta > scrollTop) {
        // Scrolling up, but this will take us past the top.
        $this.scrollTop(0);
        return prevent();
    }
});

In essence, what this does is to detect which direction the scrolling is being requested in (based on the originalEvent.wheelDelta: positive = up, negative = down). If the requested delta of the mousewheel event would move scrolling past the top or bottom of the <div>, cancel the event.

In IE, especially, scrolling events which go past a child element's scrollable area then roll up to parent elements, and the scrolling continues regardless of the event being canceled. Because we cancel the event in any case, and then control the scrolling on the child through jQuery, this is prevented.

This is loosely based on the way that this question solves the problem, but does not require the plugin, and is cross-browser compliant with IE9+.

Here is a working jsFiddle demonstrating the code in-action.

Here is a working jsFiddle demonstrating the code in-action, and updated to work with IE.

Here is a working jsFiddle demonstrating the code in-action, and updated to work with IE and FireFox. See this post for more details about the necessity of the changes.

于 2013-05-01T19:07:20.987 回答
1

也许看看

如何暂时禁用滚动?

这是停止和激活滚动的示例

于 2013-05-01T18:08:33.297 回答