带有嵌套元素的 jQuery 悬停事件嵌套、元素、事件、jQuery

由网友(我服许仙敢日蛇)分享简介:我目前有如下基本的、普通的菜单树:I've currently got your basic, run-of-the-mill menu tree as follows:homeSome controls...

我目前有如下基本的、普通的菜单树:

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");
        }
);
阅读全文

相关推荐

最新文章