问题
I have a menu in which only one item has a sublist. Here is the HTML code:
<div id="menu">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">About</a>
<ul>
<li><a href="#">Example One</a></li>
<li><a href="#">Example Two</a></li>
<li><a href="#">Example Three</a></li>
</ul>
</li>
</ul>
</div>
I would like to slideDown
the menu and stay on, when the mouse is on the menu or submenu. So the following is working good, but I want the same thing with hover and not click.
$('#menu ul li').click(function() {
$('#menu ul li ul').slideToggle('slow', function() {
});
});
I tried with hover but it's very buggy, here is the code too:
$("#menu ul li").hover(
function () {
$("#menu ul li ul").slideDown('slow');
},
function () {
$("#menu ul li ul").slideUp('slow');
}
);
I tried to add .stop(true, true)
or $("#menu ul li ul").css("display", "block");
after the slideDown
but it's still buggy.
CSS
#menu ul {
list-style: none;
}
#menu ul li {
display: block;
float: left;
padding: 0;
margin: 0 30px;
}
#menu ul li a {
color: #8b4513;
text-decoration: none;
font-size: 16px;
}
#menu ul li a:hover {
text-decoration: underline;
}
#menu ul li a img {
position: relative;
top: 2px;
left: -4px;
}
#menu ul li ul {
position: absolute;
width: 151px;
height: 90px;
top: 59px;
left: 300px;
padding: 10px 0 0 0;
background: url(gfx/submenu.png) no-repeat;
z-index: 1;
}
#menu ul li ul li {
height: 27px;
float: none;
margin: 0 25px;
}
回答1:
Check it out live
HTML
<div id="menu">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">About</a>
<ul>
<li><a href="#">Example One</a></li>
<li><a href="#">Example Two</a></li>
<li><a href="#">Example Three</a></li>
</ul>
</li>
</ul>
</div>
Jquery
$("#menu ul li").hover(
function () {
$(this).children("ul").stop(true,true).slideDown('slow');
},
function () {
$(this).children("ul").stop(true,true).slideUp('slow');
}
);
回答2:
Hover is triggered everytime the mouse moves over the element. Use enter/leave instead :
$("#menu ul li").mouseenter(
function () {
$("#menu ul li ul").slideDown('slow');
}
);
$("#menu ul li").mouseleave(
function () {
$("#menu ul li ul").slideUp('slow');
}
);
回答3:
Fiddle Demo: http://jsfiddle.net/ZMLyz/
$('#menu ul li').mouseenter(function() {
$(this).find('ul').slideDown('slow');
});
$('#menu ul li').mouseleave(function() {
$(this).find('ul').slideUp('slow');
});
来源:https://stackoverflow.com/questions/8228224/jquery-menu-toggleslide-with-hover