我有下面的代码,但我的问题是,当我将鼠标悬停在一个菜单上的所有子菜单在下拉列表中打开时,我如何只在我点击的特定菜单按钮上激活toggleClass:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("ul li").hover(function() {
// remove classes from all
$("nav li:first").toggleClass("active");
});
});
</script>
<style type="text/css">
.container nav li {display: none;}
.container nav li.active {display:block;}
</style>
<div class="container">
<ul>
<li>
<span>1</span>
<nav><li>sub 1</li>
</nav>
</li>
<li>
<span>2</span>
<nav><li>sub 1</li>
<li>sub 2</li>
</nav>
</li>
</ul>
</div>
答案 0 :(得分:0)
更改
$("nav li:first").toggleClass("active");
to:
$("nav li",this).toggleClass("active");
最终代码:
$(document).ready(function() {
$("ul li").hover(function() {
// remove classes from all
$("nav li",this).toggleClass("active");
})
})
&#13;
.container nav li {display: none;}
.container nav li.active {display:block;}
&#13;
<div class="container">
<ul>
<li>
<span>1</span>
<nav>
<li>sub 1</li>
</nav>
</li>
<li>
<span>2</span>
<nav>
<li>sub 1</li>
<li>sub 2</li>
</nav>
</li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
让<nav>
显示隐藏而不是<li>
。因此,在<nav>
标记上应用活动类。
请查看以下代码段了解更多详情。相应地改变了css和jquery代码。
$(function() {
$("ul li").hover(function() {
$("nav").removeClass("active");
// remove classes from all
$(this).find("nav").toggleClass("active");
});
});
.container nav{display: none;}
.container nav.active {display:block;padding-left:25px;}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<div class="container">
<ul>
<li>
<span>1</span>
<nav><li>sub 1</li>
</nav>
</li>
<li>
<span>2</span>
<nav>
<li>sub 1</li>
<li>sub 2</li>
</nav>
</li>
</ul>
</div>
答案 2 :(得分:0)
您只能使用CSS来实现此目的,请按照以下代码
<强> HTML:强>
<div class="container">
<ul>
<li>
<a href="#">menu1</a>
<nav>
<li>sub 1</li>
</nav>
</li>
<li>
<a href="#">menu2</a>
<nav>
<li>sub 1</li>
<li>sub 2</li>
</nav>
</li>
</ul>
</div>
<强> CSS:强>
li{
transition:0.3s ease-In-Out;
cursor:pointer;
}
.container nav li {
display: none;
}
.container nav li.active {
display:block;
}
ul li:hover nav li{
display:block;
}
点击此链接进行实时演示: https://jsfiddle.net/1235aamp/