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



我正在尝试使用javascript中的自定义元素创建一个Accordion。

下面提到的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>

  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
  • https://css-tricks.com/quick-reminder-that-details-summary-is-the-easiest-way-ever-to-make-an-accordion/

<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将触发该事件!导致一个漂亮的无休止循环

相关内容

  • 没有找到相关文章

最新更新