我正在为我的网站创建一个下拉菜单,并使用jQuery slideToggle。我让它适用于导航中的每个单独类别(当点击navparent时,navhild切换),但是当点击其他父项时,前一个子div保持打开状态。我想在点击父级时关闭其他div。
jQuery(document).ready(function($) {
$('.navparent a').click(function(){
$(this).parent().find('.navchild').slideToggle(90);
<div class="navmobile">
<div class="navparent">
<a href="#">
<img src="/source.png" alt="Parent" title="Parent" />
<br />Parent
</a>
<div class="navchild">
<ul> <li><a href="#">Child</a></li></ul>
</div>
</div>
<div class="navparent">
<a href="#">
<img src="/source.png" alt="Parent" title="Parent" />
<br /> Parent
</a>
<div class="navchild">
<ul> <li><a href="#">Child</a></li></ul>
</div>
</div>
</div>
答案 0 :(得分:1)
单击父级时,您可以简单地隐藏所有子div。
$('.navmobile').find('.navchild').hide()
答案 1 :(得分:0)
您可以添加一行来隐藏所有.navchild
元素,然后点击该元素就会打开。
jQuery(document).ready(function($) {
$('.navchild').hide();
$('.navparent a').click(function(){
$(this).parent().find('.navchild').slideToggle(90);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="navmobile">
<div class="navparent">
<a href="#">
<img src="/dcls_rebuild/themes/custom/dcls/images/mylib_color.png" alt="My Library" title="My Library" />
<br /> MY LIBRARY
</a>
<div class="navchild">
<ul> {{ page.main_navigation }}<li><a href="#">testestsetsetestsetsetsetsetsetes</a></li></ul>
</div>
</div>
<div class="navparent">
<a href="#">
<img src="/dcls_rebuild/themes/custom/dcls/images/mylib_color.png" alt="My Library" title="My Library" />
<br /> MY LIBRARY
</a>
<div class="navchild">
<ul> {{ page.main_navigation }}<li><a href="#">testestsetsetestsetsetsetsetsetes</a></li></ul>
</div>
</div>
</div>
或者您可以将CSS中的.navchild
元素默认设置为隐藏。 (通常是处理此问题的更有效方法)。
jQuery(document).ready(function($) {
$('.navparent a').click(function(){
$(this).parent().find('.navchild').slideToggle(90);
});
});
.navchild { display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="navmobile">
<div class="navparent">
<a href="#">
<img src="/dcls_rebuild/themes/custom/dcls/images/mylib_color.png" alt="My Library" title="My Library" />
<br /> MY LIBRARY
</a>
<div class="navchild">
<ul> {{ page.main_navigation }}<li><a href="#">testestsetsetestsetsetsetsetsetes</a></li></ul>
</div>
</div>
<div class="navparent">
<a href="#">
<img src="/dcls_rebuild/themes/custom/dcls/images/mylib_color.png" alt="My Library" title="My Library" />
<br /> MY LIBRARY
</a>
<div class="navchild">
<ul> {{ page.main_navigation }}<li><a href="#">testestsetsetestsetsetsetsetsetes</a></li></ul>
</div>
</div>
</div>
.navchild { display: none; }
答案 2 :(得分:0)
当你点击一个父节点时,让jQuery隐藏除了一个切换的所有子节点:
jQuery(document).ready(function($) {
$('.navchild').slideToggle(90);
$('.navparent a').click(function(e) {
e.preventDefault();
// determine what div is open
var $this = $(this).parent().find('div');
// hide all divs except this one
$(".navparent div").not($this).hide();
// toggle selected div
$this.slideToggle(90);
});
});