簡體   English   中英

Javascript 嵌套可折疊 div

[英]Javascript nested collapsible divs

我正在創建一個可折疊的 div,其中嵌套了另一個可折疊的 div:

<button class="collapsible">Expand First Panel</button>

<div class="firstPanel">
    <div class="fistPanelContent"> ••• </div>
        
    <button>Expand Second Panel</button>

    <div class="secondPanel">
        Content of the second panel
    </div>
</div>

單擊第一個按鈕時, firstPanel div 應展開,單擊嵌套的第二個按鈕時, secondPanel div 應展開。

我已經設法通過使用overflow: hidden; 和一個腳本來改變 div 的最大高度:

<script>
var allCollapsibles = document.getElementsByClassName("collapsible");

// Iterate through the collapsibles
var index;
for (index = 0; index < allCollapsibles.length; index++) {

    // Add expansion toggle
    allCollapsibles[index].addEventListener("click", function() {
        // Set max height for collapsible element
        var expandableContent = this.nextElementSibling;
        if (expandableContent.style.maxHeight) {
            expandableContent.style.maxHeight = null;
        } else {
            expandableContent.style.maxHeight = expandableContent.scrollHeight + "px";
        }
    });
}
</script>

...但這不適用於第二個擴展 div,因為我已經設置了第一個 div 的最大高度

我怎樣才能讓第二個 div 擴展,而它在第一個 div 內?

這是您的標記的解決方案。 只需添加和刪除 class 之類的show而不是沿着道路進行高度計算,這要簡單得多。 然后,您可以添加或刪除 class show ,具體取決於項目是否已經具有 class。 使用 css 您可以隱藏或顯示該項目。

 var allCollapsibles = document.querySelectorAll('.collapsible'); allCollapsibles.forEach( item => { item.addEventListener("click", function() { if(this.nextElementSibling.classList.contains('show')) { this.nextElementSibling.classList.remove('show') } else { this.nextElementSibling.classList.add('show') } }); });
 .firstPanel, .secondPanel { display: none; }.firstPanel.show, .secondPanel.show { display: block; }
 <button class="collapsible">Expand First Panel</button> <div class="firstPanel"> <div class="fistPanelContent"> ••• </div> <button class="collapsible">Expand Second Panel</button> <div class="secondPanel"> Content of the second panel </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM