如果我无法注册自定义元素,我注意到我仍然可以:使用CSS设置未注册元素的样式使用JS将事件添加到未注册的元素等例子:// REGISTER <my-custom-element-1>class MyRegisteredCustomElement1 extends HTMLElement { constructor() { super(); }};customElements.define('my-custom-element-1', MyRegisteredCustomElement1);// ATTACH EVENT LISTENERS TO BOTH CUSTOM ELEMENTSconst myCustomElement1 = document.getElementsByTagName('my-custom-element-1')[0];const myCustomElement2 = document.getElementsByTagName('my-custom-element-2')[0];const customElementAlert = (e) => { switch (e.target.nodeName.toLowerCase()) { case ('my-custom-element-1') : console.log('I\'m a registered custom element and I can be scripted and styled.'); break; case ('my-custom-element-2') : console.log('I\'m an unregistered custom element. Nevertheless, I can be scripted and styled TOO.'); break; }}myCustomElement1.addEventListener('click', customElementAlert, false);myCustomElement2.addEventListener('click', customElementAlert, false);:not(:defined) { border: 1px dashed rgb(0, 0, 0);}my-custom-element-1,my-custom-element-2 { float: left; display: inline-block; width: 100px; height: 100px; margin-right: 12px; padding: 6px; text-align: center; font-weight: bold; cursor: pointer;}my-custom-element-1 { color: rgb(255, 255, 255); background-color: rgb(255, 0, 0);}my-custom-element-1::after { content: 'I\'m a registered custom element.\A CLICK ME';}my-custom-element-2 { background-color: rgb(255, 255, 0);}my-custom-element-2::after { content: 'I\'m an unregistered custom element.\A CLICK ME';}<my-custom-element-1></my-custom-element-1><my-custom-element-2></my-custom-element-2>如果未注册的自定义元素可以设置样式和脚本,那么注册自定义元素具体可以实现什么功能?
1 回答

MYYA
TA贡献1868条经验 获得超4个赞
基本上,它将元素与您为其设置的类相关联。它:
允许使用生命周期回调,例如
connectedCallback
(和disconnectedCallback
)允许在构造函数中自定义逻辑和属性。
您创建的元素my-custom-element-2
只是一个常规 HTML 元素,没有您为其指定的特定类。my-custom-element-2
如果你检查 DOM,你会看到is的类,而isHTMLElement
的类。my-custom-element-1
myRegisteredCustomElement1
添加回答
举报
0/150
提交
取消