问题
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
回答1:
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");
}
);
回答2:
You can actually do this without js although you would need the js for ie6.
something like this might work:
$(this).children('div').css("display", "block");
or even:
$(this).children('div').show();
Here 'this' is the li.
来源:https://stackoverflow.com/questions/1327711/jquery-hover-event-with-nested-elements