如何获得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 -->
单击复选框后,属性"checked“的值应该会更改。然后我想得到它的价值。
发布于 2019-12-06 16:11:01
首先,当您使用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 -->
属性的工作原理:布尔属性(如checked、disabled、hidden )的工作方式如下:属性的实际value是无关的。属性的presence表示true,缺席表示false。
还请注意,在常规复选框中,属性checked只反映复选框的初始状态。当它发生变化时,这不会反映到属性中!您真正感兴趣的不是checked 属性,而是checked 属性。
https://stackoverflow.com/questions/59215340
复制相似问题