gpt4 book ai didi

javascript - 创建自定义输入元素

转载 作者:太空狗 更新时间:2023-10-29 13:05:43 24 4
gpt4 key购买 nike

我正在尝试创建一个自定义组件来扩展 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 来做到这一点, 创建 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>

关于javascript - 创建自定义输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com