我想用同一个类一个一个地打开和关闭两个单独的 div。
下面的例子,当我第一次点击opentab
时,content 1会第一次打开,第二次点击content 2会第二次打开。
按照content 2 和content 1 一个一个的关闭div。
评论进一步澄清。提前致谢。
$(document).ready(function() {
$(".opentab").on('click', function () {
$('.tabcontent').toggle('show');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="opentab" id="opentab">Open tab</a>
<div class="tabcontent">
Content 1
</div>
<div class="tabcontent">
Content 2
</div>
最佳答案
因为您需要知道您要去的“方向”(即如果下一次点击应该是打开或关闭元素),我建议使用 bool 变量来跟踪。我们称其为 isClosing
。
从逻辑上讲,您总是在做以下两件事之一:
- 如果关闭,隐藏最后可见
- 如果打开,显示隐藏的第一个
(代码中包含注释)
let isClosing = true; //We need to know if we're "closing" or "opening" the items
$(".opentab").on('click', function() {
$(".tabcontent").finish(); //Skip animations if pressed rapidly
const $elementToToggle = isClosing
? $('.tabcontent:visible').last() //If "closing", toggle the last visible
: $('.tabcontent:hidden').first(); //Otherwise, toggle the first hidden
$elementToToggle.toggle('show', () => { //Callback to wait for animation to complete
if (!$(".tabcontent:visible").length) isClosing = false; //All hidden, switch to "opening"
else if (!$(".tabcontent:hidden").length) isClosing = true; //All visible, switch to "closing"
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="opentab" id="opentab">Open tab</a>
<div class="tabcontent">Content 1</div>
<div class="tabcontent">Content 2</div>
<div class="tabcontent">Content 3</div>
<div class="tabcontent">Content 4</div>
关于javascript - jQuery 打开关闭两个单独的 div 一个一个地使用相同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56520086/