简体   繁体   English

如何在 Web 组件中创建手风琴自定义元素

[英]How to create Accordion custom element in web component

I am trying to create an Accordion using the custom element in javascript.我正在尝试使用 javascript 中的自定义元素创建一个手风琴。

the below mentioned HTML as I have written in the HTML下面提到的 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>

this code how to create using the custom element?此代码如何使用自定义元素创建?

If you can use a Modern Custom Element, your Browser will also know <details> and <summary>如果您可以使用现代自定义元素,您的浏览器也会知道<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>

Note: There is a toggle Event you can try (with useCapture=true ), but toggleAttribute will trigger that Event!注意:您可以尝试一个toggle事件(使用useCapture=true ),但toggleAttribute将触发该事件! Causing a nice endless loop造成一个很好的无限循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM