Recreating CSS pseudo-classes in jQuery
I am trying to add a little animation with jQuery to my navigation bar. Right now I have the sub menus of the nav bar changing from display:none to display:block with the css :hover pseudo-class. As I said, I am trying to do this with jQuery, so I need to create a selector that was similar to the one I used in my css. The selector I was using that would only display it's child list is:
#nav ul li:hover > ul
And this worked perfectly, however I obviously can not use the :hover pseudo-class within a jQuery selector, I have tried to use the .hover() method like this (this is without any animations yet):
$('#nav ul li').hover(开发者_开发百科function() {
$('#nav ul li').children('ul').css('display','block');
}, function() {
$('#nav ul li').children('ul').css('display','none');
});
However, this shows all the sub menus if I hover over any of the list items. Here are a couple of jsfiddle examples:
What it looks like with css (and what I want to recreate with jQuery):http://jsfiddle.net/FHdLC/
The result of the jQuery code above: http://jsfiddle.net/LBK3T/
Thanks very much for any help you can provide!
Use this
to refer to the current element inside the .hover()
handlers, like this:
$('#nav ul li').hover(function() {
$(this).children('ul').css('display','block');
}, function() {
$(this).children('ul').css('display','none');
});
Here's your example working with the code above :)
Also, you can shorten it down even further using just .toggle()
, like this:
$('#nav ul li').hover(function() {
$(this).children('ul').toggle();
});
You can test the .toggle()
version here
精彩评论