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

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

问题描述

 < ul ID = NAV > 
< li>
< a href =#>主页< / a>
< div class =controls>有些控件会放在这里< / div>
< ul>
< li>
< a href =#>商品1< / a>
< div class =controls>有些控件会放在这里< / div>
< / li>
< li>
< a href =#>第2项< / a>
< div class =controls>有些控件会放在这里< / div>
< / li>
< / ul>
< / li>
< / ul>

带有controls类的div是隐藏起来的。我想要发生的事情是,当你将鼠标悬停在某个li上时,相应li的控件显示(当你移开鼠标时,它们会再次隐藏)。当鼠标悬停在某个嵌套li上时,会出现问题,它也是父母控件。这里是我使用的jQuery:

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

感谢您的帮助。
Remy

解决方案

尝试停止悬停函数中的事件传播以防止事件冒泡到父项。您可能还想查看 hoverIntent 插件来解决闪烁问题,

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


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>

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");
        }
    );

Thanks for your help. Remy

解决方案

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天全站免登陆