【问题标题】:How to restrict scrolling to the div that mouse is currently hovering?如何限制滚动到鼠标当前悬停的 div?
【发布时间】:2016-02-01 15:04:24
【问题描述】:

我有一个可滚动的 div 名称,每当我将鼠标悬停在它上面时,我希望滚动仅限于该 div,以便在到达 div 的顶部/底部后,滚动将停留在 div 上。我使用了以下代码:

<div class="scrollable" style="overflow-y: scroll; height: 2px;" 
 onmouseover="document.body.style.overflow='hidden'" 
 onmouseout="document.body.style.overflow='auto'" >
   Some text<br>sometext<br>sometext 
</div>

这样做可以完成工作,但唯一的问题是主滚动条被隐藏,每次我将鼠标悬停在“.scrollable”上时网页看起来很奇怪

同样使用window.onwheel=function(){return false;} 也无济于事,因为它会阻止任何元素的滚动。

有没有办法只在悬停的 div 上启用滚动而不在其他 div 上启用滚动,同时保持主页滚动条可见?

谢谢

【问题讨论】:

  • 我认为你不需要做任何事情,这种行为是默认的。
  • 当我到达 div 滚动的底部或顶部时,它真的不会进一步移动主页
  • 然后让滚动条到整个页面总是隐藏像这样stackoverflow.com/questions/16670931/…
  • 我想过,尝试过,但在我的网站上看起来不太好,我想知道 facebook 是如何做到的,当我打开我的聊天框并在其中滚动时,滚动仅在其中有效,而即使我在聊天框的底部/顶部滚动,也保持主页的滚动条可见且不受影响。这正是我想要的

标签: javascript jquery html css hover


【解决方案1】:

您可以在不隐藏滚动条的情况下禁用滚动,请查看this 帖子。

使用 jQuery,这将导致:

$(".scroll").hover(function() {
  var oldScrollPos = $(window).scrollTop();

  $(window).on('scroll.scrolldisabler', function(event) {
    $(window).scrollTop(oldScrollPos);
    event.preventDefault();
  });
}, function() {
  $(window).off('scroll.scrolldisabler');
});

签出it

【讨论】:

  • 没问题,我的荣幸:)
【解决方案2】:

对我来说,希望可以工作

        $('body').on('mousewheel', '.someDIVClass', (e: any) => {    
            if (e.originalEvent.wheelDelta / 120 > 0) {
                // You can get scroll value here to do other things
            }
            else {
                // You can get scroll value here to do  other things
            }    

            // This will prevent window to scroll
            e.preventDefault();
            e.stopPropagation();    
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2011-10-03
    相关资源
    最近更新 更多