【问题标题】:Create a custom input element创建自定义输入元素
【发布时间】:2019-09-23 21:10:42
【问题描述】:
我正在尝试创建一个扩展 HTMLInputElement 组件的自定义组件,但没有呈现任何内容。
class myInput extends HTMLInputElement {};
customElements.define('my-input', myInput, {
extends: 'input'
});
<my-input type="text"></my-input>
我在这里错过了什么?
【问题讨论】:
标签:
javascript
html
custom-element
【解决方案1】:
您所期望的没有发生,因为这不是扩展已经内置元素的正确方法。
正如 MDN 文档所述,您需要将内置标记保留在 DOM 中,并将其影响为 is 属性。
通过关注现场输入来查看下面的sn-p。
class spotInput extends HTMLInputElement {
constructor(...args) {
super(...args);
this.addEventListener('focus', () => {
console.log('Focus on spotinput');
});
}
};
customElements.define('spot-input', spotInput, {
extends: 'input',
});
<input type="text" placeholder="simple input">
<input is="spot-input" type="text" placeholder="spot input">
但我猜你希望被允许使用<spot-input> 标签。您可以通过附加a shadow DOM、创建an autonomous element 并将其附加到<input> 来做到这一点。
class spotInput extends HTMLElement {
constructor(...args) {
super(...args);
// Attaches a shadow root to your custom element.
const shadowRoot = this.attachShadow({mode: 'open'});
// Defines the "real" input element.
let inputElement = document.createElement('input');
inputElement.setAttribute('type', this.getAttribute('type'));
inputElement.addEventListener('focus', () => {
console.log('focus on spot input');
});
// Appends the input into the shadow root.
shadowRoot.appendChild(inputElement);
}
};
customElements.define('spot-input', spotInput);
<input type="number">
<spot-input type="number"></spot-input>
那么,如果你检查 DOM 树,你应该有:
<input type="number">
<spot-input type="number">
#shadow-root (open)
<input type="number">
</spot-input>