簡體   English   中英

如何從組件的 ShadowDOM 的元素中獲取屬性

[英]How to get Properties from an Element of the ShadowDOM of my Component

如何獲取 ShadowDOM 中輸入元素的“已檢查”屬性值。

 class BitBoxComponent extends HTMLElement { static get observedAttributes() { return ["checked"]; } constructor() { super(); this.inputElem = document.createElement("INPUT"); this.inputElem.setAttribute("type", "checkbox"); this.inputElem.setAttribute("checked", false); // this.inputElem.style.border = "solid 1px grey"; const style = document.createElement("style"); style.textContent = ``; const shadow = this.attachShadow({ mode: "open" }); shadow.appendChild(style); shadow.appendChild(this.inputElem); } attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; var isTrueSet = newValue == "true"; this.inputElem.checked = isTrueSet; } } customElements.define("bit-box", BitBoxComponent); document.addEventListener('DOMContentLoaded', () => { const bit = document.getElementById("bit-7").getAttribute("checked"); console.log(bit); })
 <bit-box id="bit-7"></bit-box> <bit-box id="bit-6"></bit-box> <bit-box id="bit-0"></bit-box> <!-- https://github.com/mateusortiz/webcomponents-the-right-way -->

單擊復選框后,屬性“已檢查”的值應更改。 然后我想獲得與之合作的價值。

首先,當您使用mode: 'open' ,不需要存儲引用 - 它在this.shadowRoot自動可用(也從外部)。

接下來,為checked創建一個getter 和setter,這使得checked表現得像一個真正的布爾屬性

 class BitBoxComponent extends HTMLElement { constructor() { super(); this.inputElem = document.createElement("INPUT"); this.inputElem.type = "checkbox"; this.inputElem.checked = false; this.inputElem.addEventListener('change', () => { this.checked = this.inputElem.checked; }) this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(this.inputElem); } static get observedAttributes() { return ["checked"]; } attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; if (oldValue === null) { // attribute was added this.inputElem.checked = true; } else if (newValue === null) { // attribute was removed this.inputElem.checked = false; } const event = new CustomEvent('bit-box-change', { detail: { checked: this.checked } }); this.dispatchEvent(event); } get checked() { return this.inputElem.checked; } set checked(bool) { if (bool) { this.setAttribute('checked', ''); } else { this.removeAttribute('checked') } } } customElements.define("bit-box", BitBoxComponent); document.querySelectorAll('bit-box').forEach(box => box.addEventListener('bit-box-change', (event) => { console.log(event.detail.checked); }) );
 <bit-box id="bit-7"></bit-box> <bit-box id="bit-6"></bit-box> <bit-box id="bit-0"></bit-box> <!-- https://github.com/mateusortiz/webcomponents-the-right-way -->

屬性如何工作: 布爾屬性,如checkeddisabledhidden是這樣工作的: 屬性的實際value無關緊要的 屬性的存在意味着true不存在意味着 false 。

還要注意的是定期復選框,在屬性checked也永遠只能反映復選框的初始狀態 當它發生變化時,這不會反映到屬性中! 您真正感興趣的不是checked屬性,而是checked屬性

暫無
暫無

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

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