我将参考按钮1-2和B1和B2来解释我的问题。
点击B1将打开列表。
当B1打开时点击B2,将关闭B1并打开B2。
这是问题所在: 当B1打开时点击B1,将关闭并再次打开B1。我希望它在点击时关闭,如果它是打开的。我怎样才能做到这一点?
$(document).ready(function() {
$(".dropdown").click(function() {
$(".dropdown-container").slideUp('slow')
$(this).closest('.dropdown').find('.dropdown-container').slideDown('slow');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<div class="dropdown btn">
<span>Button 1</span>
<div class="dropdown-container">
<a href="#">1.1</a>
<a href="#">1.2</a>
<a href="#">1.3</a>
<a href="#">1.4</a>
</div>
</div>
<div class="dropdown btn">
<span>Button 2</span>
<div class="dropdown-container">
<a href="#">2.1</a>
<a href="#">2.2</a>
<a href="#">2.3</a>
<a href="#">2.4</a>
</div>
</div>
<div class="dropdown btn">
<span>Button 3</span>
<div class="dropdown-container">
<a href="#">3.1</a>
<a href="#">3.2</a>
<a href="#">3.3</a>
<a href="#">3.4</a>
</div>
</div>
</nav>
答案 0 :(得分:0)
您需要使用.not()
排除当前元素的容器,并使用.slideToggle()
$(document).ready(function() {
$(".dropdown").click(function() {
var childCointainer = $(this).find('.dropdown-container');
$(".dropdown-container").not(childCointainer).slideUp('slow');
childCointainer.slideToggle('slow');
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<div class="dropdown btn">
<span>Button 1</span>
<div class="dropdown-container">
<a href="#">1.1</a>
<a href="#">1.2</a>
<a href="#">1.3</a>
<a href="#">1.4</a>
</div>
</div>
<div class="dropdown btn">
<span>Button 2</span>
<div class="dropdown-container">
<a href="#">2.1</a>
<a href="#">2.2</a>
<a href="#">2.3</a>
<a href="#">2.4</a>
</div>
</div>
<div class="dropdown btn">
<span>Button 3</span>
<div class="dropdown-container">
<a href="#">3.1</a>
<a href="#">3.2</a>
<a href="#">3.3</a>
<a href="#">3.4</a>
</div>
</div>
</nav>
&#13;
答案 1 :(得分:0)
您可以使用.not选择器排除点击的下拉菜单,不要向上滑动
$(document).ready(function() {
$(".dropdown").click(function() {
var $dropdown = $(this).closest('.dropdown').find('.dropdown-container');
$dropdown.slideToggle('slow');
$(".dropdown-container").not($dropdown).slideUp('slow');
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<div class="dropdown btn">
<span>Button 1</span>
<div class="dropdown-container">
<a href="#">1.1</a>
<a href="#">1.2</a>
<a href="#">1.3</a>
<a href="#">1.4</a>
</div>
</div>
<div class="dropdown btn">
<span>Button 2</span>
<div class="dropdown-container">
<a href="#">2.1</a>
<a href="#">2.2</a>
<a href="#">2.3</a>
<a href="#">2.4</a>
</div>
</div>
<div class="dropdown btn">
<span>Button 3</span>
<div class="dropdown-container">
<a href="#">3.1</a>
<a href="#">3.2</a>
<a href="#">3.3</a>
<a href="#">3.4</a>
</div>
</div>
</nav>
&#13;