jQuery slideToggle一次多个Div

时间:2017-10-09 11:50:18

标签: javascript jquery

这是我的代码,



$(document).ready(function (e) {
$('.showhide').click(function(e) {
$(this).nextAll('.dropdown:lt(1)').slideToggle(100);
e.stopPropagation();
});
$(window).click(function(e) {
var container = $(".dropdown");
if (container.is(':visible') && !$(e.target).closest('.dropdown').length) {
container.hide();
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="showhide">Button</a>
<div class="dropdown">
<a href="#">Update</a>
<a href="#">Delete</a>
</div>


<a class="showhide">Button</a>
<div class="dropdown">
<a href="#">Update</a>
<a href="#">Delete</a>
</div>
&#13;
&#13;
&#13;

此代码为Opening&amp;关闭div很好。此外,如果我在div打开时点击外面,它就会关闭它们。

但问题是,如果我一个接一个地点击它们,它会一次打开多个div。我如何一次只打开一个div?

2 个答案:

答案 0 :(得分:1)

点击任意siblings元素后,您可以隐藏showhide

$('.dropdown').hide()

$('.showhide').click(function(e) {
  e.stopPropagation();
  $(this).siblings('.showhide').next('.dropdown').slideUp()
  $(this).next('.dropdown').slideToggle(100);
});

$(window).click(function(e) {
  var container = $(".dropdown");
  if (container.is(':visible') && !$(e.target).closest('.dropdown').length) {
    container.hide();
  }
});
a.showhide {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="showhide">Button</a>
<div class="dropdown">
  <a href="#">Update</a>
  <a href="#">Delete</a>
</div>


<a class="showhide">Button</a>
<div class="dropdown">
  <a href="#">Update</a>
  <a href="#">Delete</a>
</div>

答案 1 :(得分:0)

尝试这样的事情

&#13;
&#13;
$(document).ready(function (e) {


$('.showhide').click(function(e) {
el = $(this).nextAll('.dropdown:lt(1)')
el.slideToggle(100);
$('.dropdown').not(el).hide();//hide all execpt the current one
e.stopPropagation();
});
$(window).click(function(e) {
var container = $(".dropdown");
if (container.is(':visible') && !$(e.target).closest('.dropdown').length) {
container.hide();
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="showhide">Button</a>
<div class="dropdown">
<a href="#">Update</a>
<a href="#">Delete</a>
</div>


<a class="showhide">Button</a>
<div class="dropdown" style="display:none">
<a href="#">Update</a>
<a href="#">Delete</a>
</div>
&#13;
&#13;
&#13;