创建自定义输入元素

Create a custom input element

我正在尝试创建一个自定义组件来扩展 HTMLInputElement 组件,但没有呈现。

class myInput extends HTMLInputElement {};

customElements.define('my-input', myInput, {
  extends: 'input'
});
<my-input type="text"></my-input>

我在这里错过了什么?

您所期望的并没有发生,因为这不是扩展已内置元素的正确方法。

如 MDN 文档所述,您需要将内置标签保留在 DOM 中并影响它的 is 属性。

通过关注 点输入 查看下面的代码片段。

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, creating 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>