2022年5月8日 星期日

[研究]HTML 的 details 和 summary 顯示展開收合(手風琴(Accordion)、折疊(Collapse))效果

[研究]HTML 的 details 和 summary 顯示展開收合(手風琴(Accordion)、折疊(Collapse))效果

2022-05-08

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C#

********************************************************************************

H2.html

<details>
    <summary>title 1</summary>  
    <p>content 1</p>
</details>
<details>
    <summary>title 2</summary>
    <p>content 2</p>
</details>
<details>
    <summary>title 3</summary>
    <p>content 3</p>
</details>


結果


********************************************************************************

如果希望同一時間只會展開一個,就需要靠 JavaScript 幫忙。

H3.html

<details class="details">
    <summary>title 1</summary>
    <p>content 1</p>
</details>
<details class="details">
    <summary>title 2</summary>
    <p>content 2</p>
</details>
<details class="details">
    <summary>title 3</summary>
    <p>content 3</p>
</details>

<script>
  var details = Array.from(document.querySelectorAll('.details'));  
  details.forEach((detail) => {
    detail.addEventListener('click', (e) => {
      var active = details.find(d => d.open);
      if (!e.currentTarget.open && active) {
        active.open = false;
      }
    });
  });
</script>


H4.html

<details class="detailsOpen">
    <summary>title 1</summary>
    <p>content 1</p>
</details>
<details class="detailsOpen">
    <summary>title 2</summary>
    <p>content 2</p>
</details>
<details class="detailsOpen">
    <summary>title 3</summary>
    <p>content 3</p>
</details>

<script>
  var detailItems = Array.from(document.querySelectorAll('.detailsOpen'));
  detailItems.forEach((detailItem) => {
    detailItem.addEventListener('click', (e) => {
      var active = detailItems.find(d => d.open);
      if (!e.currentTarget.open && active) {
        active.open = false;
      }
    });
  });
</script>


(完)

相關

[研究]HTML 的 details 和 summary 顯示展開收合(手風琴(Accordion)、折疊(Collapse))效果
https://shaurong.blogspot.com/2022/05/html-details-summary-accordioncollapse.html

[研究]展開收合(手風琴、Accordion)效果 (BootStrap 5)
http://shaurong.blogspot.com/2022/01/accordion-bootstrap-5.html

[研究] 頁籤(tab) (HTML + jQuery 3.5.1 + Bootstrap 3.4.1)
https://shaurong.blogspot.com/2021/02/tab-html-jquery-351-bootstrap-341.html

[研究] 頁籤(tab) (HTML + CSS3)
https://shaurong.blogspot.com/2021/02/tab-html-css3.html

[研究] 頁籤(tab) ( HTML + CSS + JavaScript + jQuery + jQuery UI)
https://shaurong.blogspot.com/2021/02/tab-html-css-javascript-jquery-jquery-ui.html

[研究] 頁籤(tab) (HTML+CSS+JavaScript+jQuery)
https://shaurong.blogspot.com/2021/02/tab-htmlcssjavascriptjquery.html

[研究] 頁籤(tab) (HTML+CSS+JavaScript)
https://shaurong.blogspot.com/2021/02/tab-htmlcssjavascript.html

沒有留言:

張貼留言