我正在尝试使用 jQuery 添加一些动画到我的导航栏。现在,我的导航栏的子菜单从 display:none 更改为 display:block ,并带有 css :hover 伪类。正如我所说,我正在尝试使用 jQuery 来完成此操作,因此我需要创建一个与我在 css 中使用的选择器类似的选择器。我使用的仅显示其子列表的选择器是:
#nav ul li:hover > ul
这工作得很好,但是我显然不能在 jQuery 选择器中使用 :hover 伪类,我尝试使用像这样的 .hover() 方法(这还没有任何动画):
$('#nav ul li').hover(function() {
$('#nav ul li').children('ul').css('display','block');
}, function() {
$('#nav ul li').children('ul').css('display','none');
});
但是,如果我将鼠标悬停在任何列表项上,这会显示所有子菜单。这里有几个 jsfiddle 示例:
css 的样子(以及我想用 jQuery 重新创建的内容):http: //jsfiddle.net/FHdLC/
上面 jQuery 代码的结果: http://jsfiddle.net /LBK3T/
非常感谢您提供的任何帮助!
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!
发布评论
评论(1)
使用
this
引用 < 中的当前元素 code>.hover() 处理程序,如下所示:这是您使用上面的代码 :)
此外,您还可以使用
.toggle( )
,如下所示:您可以测试
.toggle()< /code> 版本在这里
Use
this
to refer to the current element inside the.hover()
handlers, like this:Here's your example working with the code above :)
Also, you can shorten it down even further using just
.toggle()
, like this:You can test the
.toggle()
version here