带有嵌套元素的 jQuery 悬停事件
我目前已经得到了基本的、普通的菜单树,如下所示:
<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>
带有“controls”类的 div 首先是隐藏的。我想要发生的是,当您将鼠标悬停在 li 上时,相应 li 的控件会显示(当您将鼠标移开时,它们会再次隐藏)。当您将鼠标悬停在其中一个嵌套的 li 上时,会出现问题,它也会显示其父控件。这是我正在使用的 jQuery:
$("#nav li").hover(
function() {
$(".controls:first", this).css("display", "block");
},
function() {
$(".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");
}
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在悬停函数中停止事件传播,以防止事件冒泡到父级。您可能还想查看 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.
实际上,你可以在没有 js 的情况下做到这一点,尽管你需要 ie6 的 js。
像这样的东西可能会起作用:
甚至:
这里的“this”是 li。
You can actually do this without js although you would need the js for ie6.
something like this might work:
or even:
Here 'this' is the li.