嵌套元素悬停处理

3

大家好,我遇到了一个与嵌套元素的悬停处理有关的问题。当鼠标进入子 child div 时,祖先元素也处于 hover 状态。有没有办法在鼠标进入子元素时触发祖先元素的 hoverout 事件?

以下是我迄今为止所做的,请审核。

<style>
div
{
    border:1px solid red;
    margin:10px;
    padding:10px;
}
</style>


  <script>
      $(function() {
           $('div').each(function(){
             var current = this;
             $(this).hover(function(event){
                event.stopPropagation();// doesn't work.
                console.log('Capture for hover in ' + current.tagName + '#'+ current.id +
                    ' target is ' + event.target.id); },
               function(event){
                  event.stopPropagation();
                  console.log('Capture for hover out' + current.tagName + '#'+ current.id +
                    ' target is ' + event.target.id); });

                            });
                        });
 </script>

 <body id="greatgrandpa">                        
        <div id="grandpa">
               <div id="parent">
                  <div id="child"/>
               </div>
        </div>
 </body>

只需删除星号并在图像上运行函数?您正在循环中附加事件处理程序,该循环迭代页面上的所有元素 - adeneo
嗨,@adeneo,我刚刚更新了问题,使其更清晰。请审核一下。谢谢。 - Joe.wang
我真的不理解,但你可以将mouseenter/leave函数设置为任何你想要的东西,例如这个FIDDLE ?? - adeneo
嗨,@adeneo,想象一下,如果我们不知道body中有多少个嵌套的div元素怎么办?也许子元素还有嵌套元素。我只是演示了一个简单的情况。谢谢。 - Joe.wang
3个回答

5
.hover() 方法绑定了 mouseentermouseleave 事件的处理程序。您可以使用它在鼠标进入元素时简单地应用行为到该元素。
但是,如果您使用 mouseovermouseout 事件,则这些事件会在鼠标移动进入和移出元素及其后代时触发。
请参见http://jsfiddle.net/5yQY5/以获取您示例的替代方法。

在得到你的答案之前,这让我感到困惑。谢谢。 - Joe.wang

1
请使用mouseover和mouseout事件代替。
$(function() {
    $('div').on('mouseover', function(e){
        e.stopPropagation();
        $(this).addClass('my-bg');
    }).on('mouseout', function(e){
        $(this).removeClass('my-bg');
    })
});

示例:Fiddle

注意:无需遍历每个div并为每个div添加事件处理程序,只需调用$('div').hover(...),它将为所有div注册hover处理程序。


嗨,@Arun P Johny,你能告诉我“hoverin hoverout”和“mouseover mouseout”的区别吗?谢谢。 - Joe.wang
你可以查看像这篇文章一样的帖子:https://dev59.com/pnNA5IYBdhLWcg3wEZeT - Arun P Johny

1
你需要找出目标 DOM 是否为子元素。

示例

$(this).hover(function(e){
    if($(e.target).is('div#child'))
    {
        // your child span is being hovered over
        e.stopPropagation();
    }
    else if($(e.target).is('div#parent'))
    {
        // your parent element is being hovered over
    }
});

@Joe.wang 欢迎随时提问...我只是根据你的代码尝试回答,所以我想为什么不编辑代码并给出符合当前代码的解决方案呢。 - Dipesh Parmar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接