当鼠标悬停在绝对div上时jQuery禁用滚动 [英] jQuery disable scroll when mouse over an absolute div

查看:47
本文介绍了当鼠标悬停在绝对div上时jQuery禁用滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当鼠标悬停在div上时,我试图禁用窗口鼠标滚动功能-以便仅启用div滚动-当鼠标移离div时,将再次应用到窗口的滚动. div的位置绝对正确.

I'm trying to disable the window mouse scroll functionality when the mouse is hovering over the div - so that only div scrolling is enabled - and when mouse moves away from the div - scrolling to the window is applied again. The div is positioned absolutely.

我看过这篇帖子当鼠标光标位于div内时,使用jquery禁用鼠标滚轮功能吗?但它似乎没有提供任何答案-因此是我的问题.

I've seen this post use jquery to disable mouse scroll wheel function when the mouse cursor is inside a div? but it doesn't seem to provide any answer - hence my question.

我假设是这样的(如果仅存在这些方法):

I'm assuming it would be something like this (if only these methods existed):

$('#container').hover(function() {
     $(window).scroll().disable();
     $(this).scroll().enable();
}, function() {
     $(window).scroll().enable();
});

推荐答案

这是一个很普遍的问题,因此我正在更新以概述此处提供的答案,这可能是最适合您的.包括三种独特的解决方案.其中两个来自Amos,一个来自我自己.但是,每个操作都不同.

This has been a popular question so I am updating to give an overview of the answers provided here and which may be best for you. There are three unique solutions included. Two are from Amos and one is from myself. However, each operates differently.

  1. Amos-在主体上设置overflow:hidden.这很简单,效果很好.但是主窗口的滚动条会闪烁进出.
  2. Amos-使用javascript禁用鼠标滚轮.如果您完全不需要滚轮,那就太好了.
  3. 此答案-使用javascript仅滚动您结束的元素.如果您的内部div需要滚动,但是您不希望任何其他div滚动,则这是最佳答案.小提琴示例展示了这一点.
  1. Amos - Set overflow:hidden on body. This is simple and works great. But the main window's scrollbars will flash in and out.
  2. Amos - Use javascript to disable mouse wheel. This is great if you don't need mousewheel at all.
  3. This answer - Use javascript to scroll only the element you are over. This is the best answer if your inner div needs to scroll, but you don't want any other divs to scroll. The example fiddle showcases this.

http://jsfiddle.net/eXQf3/371/

代码的工作方式如下:

  • 在当前元素上捕获滚动事件
  • 取消滚动事件
  • 仅手动滚动当前元素

 

$('#abs').bind('mousewheel DOMMouseScroll', function(e) {
    var scrollTo = null;

    if (e.type == 'mousewheel') {
        scrollTo = (e.originalEvent.wheelDelta * -1);
    }
    else if (e.type == 'DOMMouseScroll') {
        scrollTo = 40 * e.originalEvent.detail;
    }

    if (scrollTo) {
        e.preventDefault();
        $(this).scrollTop(scrollTo + $(this).scrollTop());
    }
});​

变更日志:

  • FF支持
  • scrollTo为空检查以在发生无法预料的情况时恢复为默认行为
  • 对jQuery 1.7的支持.

这篇关于当鼠标悬停在绝对div上时jQuery禁用滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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