当我将鼠标悬停在它上面时,我试图让子菜单显示出来。目前,当我将鼠标悬停在Locations
时,它会消失。
我的演示:http://jsfiddle.net/269yqavo/
这是我的代码:
$('.main a.primary').hover(function(e){
e.preventDefault();
$(this).next().toggle();
}).hover();
.sub-menu {display:none;background:#ccc}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul class="sf-menu">
<li class="main">
<a href="" class="primary">Locations</a>
<ul class="sub-menu">
<li><a href="/location/athina/" title=
"View all posts in Athina">Athina</a></li>
<li><a href="/location/beirut/" title=
"View all posts in Beirut">Beirut</a></li>
</ul>
</li>
</ul>
答案 0 :(得分:4)
这是一个没有JS的解决方案。 只要容器悬停,只需显示子菜单。
http://jsfiddle.net/269yqavo/1/
.sub-menu {
display:none;
background:#ccc
}
.main:hover .sub-menu {
display: block;
}
答案 1 :(得分:2)
为什么不这样做?应该以不同的方式使用悬停功能。该事件应该绑定在父母身上。
$('.main a.primary').parent().hover(function(e){
$(this).find("a").next().show();
}, function () {
$(this).find("a").next().hide();
});
.sub-menu {display: none; background: #ccc}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul class="sf-menu">
<li class="main">
<a href="" class="primary">Locations</a>
<ul class="sub-menu">
<li><a href="/location/athina/" title=
"View all posts in Athina">Athina</a></li>
<li><a href="/location/beirut/" title=
"View all posts in Beirut">Beirut</a></li>
</ul>
</li>
</ul>
而不是使用JS,你可以单独使用CSS:
.sub-menu {
display: none;
background: #ccc
}
.main:hover .sub-menu {
display: block;
}
<ul class="sf-menu">
<li class="main">
<a href="" class="primary">Locations</a>
<ul class="sub-menu">
<li><a href="/location/athina/" title=
"View all posts in Athina">Athina</a></li>
<li><a href="/location/beirut/" title=
"View all posts in Beirut">Beirut</a></li>
</ul>
</li>
</ul>
答案 2 :(得分:0)
为什么你用简单的CSS来做?
HTML
<ul class="sf-menu">
<li class="main">
<a href="" class="primary">Locations</a>
<ul class="sub-menu">
<li><a href="/location/athina/" title=
"View all posts in Athina">Athina</a></li>
<li><a href="/location/beirut/" title=
"View all posts in Beirut">Beirut</a></li>
</ul>
</li>
</ul>
CSS
.sub-menu {display:none;background:#ccc}
.main:hover .sub-menu{
display:block
}
当你悬停在主类子菜单上时,这里的简单逻辑将显示
<强> JSFIDDLE 1 强>
OR
$('.sf-menu').children().hover(function(e){
$(this).find("a").next().show();
}, function () {
$(this).find("a").next().hide();
});
<强> JSFIDDLE 2 强>