带有嵌套元素的jQuery悬停事件 [英] jQuery hover event with nested elements

查看:17
本文介绍了带有嵌套元素的jQuery悬停事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前得到了您基本的、普通的菜单树,如下所示:

I've currently got your basic, run-of-the-mill menu tree as follows:

<ul id="nav">
  <li>
    <a href="#">home</a>
    <div class="controls">Some controls go here</div>
    <ul>
      <li>
        <a href="#">item 1</a>
        <div class="controls">Some controls go here</div>
      </li>
      <li>
        <a href="#">item 2</a>
        <div class="controls">Some controls go here</div>
      </li>
    </ul>
  </li>
</ul>

带有控件"类的 div 一开始是隐藏的.我想要发生的是,当您将鼠标悬停在 li 上时,相应 li 的控件会显示(当您将鼠标移开时,它们会再次隐藏).当您将鼠标悬停在一个嵌套的 li 上时会出现问题,它也会显示它的父控件.这是我正在使用的 jQuery:

The divs with the "controls" class are hidden to start with. What I want to happen is that when you hover over an li, the controls for that respective li show (when you move your mouse away, they hide again). The problem occurs when you hover over one of the nested li's, it display's it's parents controls as well. Here is the jQuery I'm using:

    $("#nav li").hover(
        function() {
            $(".controls:first", this).css("display", "block");
        },
        function() {
            $(".controls:first", this).css("display", "none");
        }
    );

感谢您的帮助.雷米

推荐答案

尝试在悬停函数中停止事件传播,以防止事件冒泡到父级.您可能还想查看 hoverIntent 插件来解决闪烁"问题如果您的悬停"元素靠得很近,则会产生悬停效果.

Try stopping event propagation in the hover function to prevent the event from bubbling up to the parent. You might also want to look at the hoverIntent plugin to solve issues of "flashing" hover effects if your "hovered" elements are close together.

$("#nav li").hover(
    function(e) {
            e.stopPropagation();
            $(".controls:first", this).css("display", "block");
        },
        function() {
            $(".controls:first", this).css("display", "none");
        }
);

这篇关于带有嵌套元素的jQuery悬停事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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