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

查看:34
本文介绍了当鼠标悬停在绝对 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();
});

推荐答案

这是一个很受欢迎的问题,所以我正在更新以概述此处提供的答案,哪些可能最适合您.包括三种独特的解决方案.两个来自阿莫斯,一个来自我自己.但是,每个操作都不同.

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 - 在 body 上设置 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 null 检查以在发生不可预见的情况时恢复到默认行为
  • 支持 jQuery 1.7.

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

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