![](/img/trans.png)
[英]toggle divs so only one is open at a time, but be able to close them all as well javascript
[英]Only one toggle open at a time?
我是JS新手,請耐心等待。
我正在嘗試創建一個基本的內容切換,但是我正努力使我的代碼一次只顯示一個切換。
我使用的代碼是:
<div>
<h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
<h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>
</div>
<div class ="toggle" id="box1">
box one content
</div>
<div class ="toggle" id="box2">
box two content
</div>
$("a").click(function(){
var myelement = $(this).attr("href")
$(myelement).slideToggle("slow");
$(".toggle:visible").not(myelement).hide();
});
一次只顯示一項。 單擊它們,您將看到:
$("a").click(function(){ var myelement = $(this).attr("href") $(myelement).slideToggle("slow"); $(".toggle:visible").not(myelement).hide(); });
<div> <h3 class = "trigger"><a href="#box1"> Heading 1</a></h3> <h3 class = "trigger"><a href="#box2"> Heading 2</a></h3> </div> <div class ="toggle" id="box1"> box one content </div> <div class ="toggle" id="box2"> box two content </div> <script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>
JSFiddle: https ://jsfiddle.net/xd146x1s/2/
如果要在開始時隱藏元素,只需使用$(".toggle").hide();
像這樣:
$(".toggle").hide(); $("a").click(function(){ var myelement = $(this).attr("href") $(myelement).slideToggle("slow"); $(".toggle:visible").not(myelement).hide(); });
<div> <h3 class = "trigger"><a href="#box1"> Heading 1</a></h3> <h3 class = "trigger"><a href="#box2"> Heading 2</a></h3> </div> <div class ="toggle" id="box1"> box one content </div> <div class ="toggle" id="box2"> box two content </div> <script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>
JSFiddle: https ://jsfiddle.net/xd146x1s/3/
為了一次顯示一個切換,您需要比slideToggle提供更多的控制,因為您要處理兩種相反的情況,即要顯示的元素的slideDown和其他的。
//By default they all will be hidden $('.toggle').hide(); $("a").on('click', function(){ //fetch the element wrapped with jQuery var $myelement = $($(this).attr("href")); //Hide all elements but the selected one //and shows it at the same time, since jQuery //returns the object right back to allow chaining $('.toggle').not($myelement.slideDown('slow')).slideUp("slow"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <h3 class = "trigger"><a href="#box1"> Heading 1</a></h3> <h3 class = "trigger"><a href="#box2"> Heading 2</a></h3> </div> <div class ="toggle" id="box1"> box one content </div> <div class ="toggle" id="box2"> box two content </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.