Maintain hover state (jQuery)
HTML:
<ul class="dropdown">
<li><a href="#">Item 1</a></li>
<li>
<a href="#">Item 2</a>
<div class="submenu">something</div>
</li>
</ul>
jQuery:
$j("ul.dropdown li").hover(function () {
$j(this).addClass("hover");
$j('div.submenu', this).css('visibility', 'visible');
}, function () {
$j(this).removeClass("hover");
$j('div.submenu', this).css('visibility', 'hidden');
});
... the menu works fine, but when the div.submenu
is shown and I move the cursor to it, the link that opened this submenu loses its 'hover' class, how do I maintain hover state on both the link and the submenu when they're open?
I tried this, but its not working:
$j("ul.dropdown li").hover(function () {
$j(this).开发者_StackOverflowaddClass("hover");
$j('div.submenu', this).css('visibility', 'visible').hover(function () {
$j(this).prev('a').addClass('hover');
}, function () {
$j(this).prev('a').removeClass('hover');
});
}, function () {
$j(this).removeClass("hover");
$j('div.submenu', this).css('visibility', 'hidden');
});
You may need to consider the submenu div also part of jQuery elements, while attaching hover effect to. May be sth like this:
$('ul.dropdown li').each(function() {
var self = $(this),
menu = $(this).find('div.submenu'),
el = menu.add(this);
el.hover(function() {
self.addClass("hover");
menu.css("visibility", "visible");
}, function() {
self.removeClass("hover");
menu.css("visibility", "hidden");
});
});
You cannot maintain the hover state on an element that you don't hover :) Try putting the div.submenu
inside the ul.dropdown li
, if it is possible. Another solution is to stop relying on hover()
and use another way of manipulating your classes. Don't use the hover()
to toggle classes, use some function to do it and call it when you need it.
In my experience, js menus are more trouble than they're worth. There's a perfectly workable CSS solution if you don't want any fancy fadein or rolldown effects.
But! This might have to do with CSS anyway. I think people are overthinking it. All you really want is for your link to still look hovered over--your display's fine. Okay. You can do this with CSS and jQuery:
ul.dropdown li:hover a,
ul.dropdown li.hover a {
/* how your link should look */
}
Now, if you have that style (.hover
is important) there already, your submenu should be disappearing on hover, too, so something else is afoot.
精彩评论