如何在 Web 组件中创建 Accordion 自定义元素

How to create Accordion custom element in web component

我正在尝试使用 javascript 中的自定义元素创建手风琴。

下面提到的 HTML 正如我在 HTML

中所写

var accordions = document.querySelectorAll(".accordion");

for (var i = 0; i < accordions.length; i++) {
  accordions[i].onclick = function () {
    this.classList.toggle('is-open');
    var content = this.nextElementSibling;
    if (content.style.maxHeight) {
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    }
  }
}
<div class="container">
  <button class="accordion">Accordian #1</button>
  <div class="accordion-content">
    <p> Content 1</p>
  </div>
</div>

此代码如何使用自定义元素创建?

如果您可以使用现代自定义元素,您的浏览器也会识别 <details><summary>

<style>
  details[open] {
    background: lightgreen;
    padding-left: 1em;
  }
  details[open] summary {
    background: green;
    color: white;
    margin-left: -1em;
  }
</style>
<my-accordion>
  <details><summary>Alpha</summary>Amazing!</details>
  <details open><summary>Bravo</summary>Note the default open attribute</details>
  <details><summary>Charlie</summary><h3>Cool!</h3>hold Ctrl Key</details>
  <details><summary>Delta</summary><B>D...</B><hr>The end</details>
</my-accordion>
<script>
  customElements.define('my-accordion', class extends HTMLElement {
    connectedCallback() {
      this.onclick = evt => {
        [...this.children].map(detail => {
          !evt.ctrlKey && detail.toggleAttribute("open", evt.target == detail);
        });
      }
    }
  });
</script>

注意:有一个 toggle 事件 你可以尝试(使用 useCapture=true),但 toggleAttribute 会触发该事件!造成一个很好的无限循环