jQuery将div悬停在另一层下面

问题描述 投票:13回答:7

是否有可能忽略所有使用jQuery绑定到它们的元素“上方”的div?例如,我有一个元素A,它有一个绑定到它的悬停事件,但是还有其他元素B,C,D在元素A上面“绝对定位”。所以当用户的鼠标移动到元素B,C时, D,即使B,C和D直接位于元素上方,也不再触发悬停事件。是否可以忽略元素B C和D?

更新:我实际上是在创建一个地图(元素A),其中元素B,C,D作为区域标签。因此,例如,对于纽约州的地图,您将具有与地图重叠的文本元素“曼哈顿”,“新泽西”等。这就是为什么即使用户将鼠标悬停在标签上,我也需要悬停。

jquery hover ignore
7个回答
30
投票

如果你可以使用CSS3,那么你可以为绝对定位的元素设置pointer-events:none,参见demo here

All modern browsers支持这个属性 - 只有IE9及以下版本和Opera Mini不支持它(在撰写本文时)。这也意味着你不会有那些可能不是你想要的元素的指针事件。


4
投票

我看到它的方式,你有几个选择:

  • 像Ivarska推荐的那样,在所有这些元素上创建一个空元素并将其用作触发器。
  • 绑定到整个页面上的mousemove并找到它“在框内”(即在目标元素上) - 基本上,重新发明悬停事件。 (但这不会给你的页面增加一些非常严重的开销)
  • 重新设计

您也可能只能绑定目标(即A)和任何可能与A重叠的元素,然后只检查另一个控件中的鼠标位置是否也假设在A控件内。比绑定到页面和检查更少的开销,但仍然超过典型。


4
投票

使用e.relatedTarget确定用户是否悬停在其中一个嵌套(绝对)元素上。如果你给地图标签一个类,可能会更容易

例如:在地图上显示悬停状态期间的标签,并仅在用户离开地图时隐藏它们

    $("#map").hover(
      function(e) { 
        $(this).find(".labels").fadeIn();
      },

      function(e) {
        if( $(e.relatedTarget).hasClass("maplabel") ) {
          //The user has hovered over a label...Do nothing (or some other function)
        } else {
          // User has left the map and isn't over a label
          $(this).find(".labels").fadeOut();
      }
    );

0
投票

我现在想到的唯一解决方案是在顶部创建一个不可见的元素并给它悬停触发器。


0
投票

您可以使A元素的z-index高于B,C和D元素的z-index。


0
投票

虽然有不同的方法来解决这个问题,但最简单的方法是将悬停事件添加到所有元素:

HTML

<div id="a" class="hover"></div>
<div id="b" class="hover"></div>
<div id="c" class="hover"></div>
<div id="d" class="hover"></div>
<div id="state">unhovered</div>

CSS

#a {
    width: 350px;
    height: 300px;
    border: 1px solid #000;
    background-color: #ccc;
}
#b {
    position: absolute;
    top: 35px;
    left: 35px;
    width: 35px;
    height: 30px;
    border: 1px solid #000;
    background-color: #cca;
}
#c {
    position: absolute;
    top: 85px;
    left: 85px;
    width: 35px;
    height: 30px;
    border: 1px solid #000;
    background-color: #cca;
}
#d {
    position: absolute;
    top: 85px;
    left: 135px;
    width: 35px;
    height: 30px;
    border: 1px solid #000;
    background-color: #cca;
}

jQuery的

$(document).ready(function(){
    $('.hover').hover(
        function(){
            $('#state').text('hovered');
        },
        function(){
            $('#state').text('unhovered');
        }
    );
});

示例:http://jsfiddle.net/userdude/H5TAG/


0
投票

其他人提到的z-index调整工作。使您希望通过悬停识别的项目的z-index更高。

© www.soinside.com 2019 - 2024. All rights reserved.