为了账号安全,请及时绑定邮箱和手机立即绑定

未注册的 HTML 自定义元素和注册的 HTML 自定义元素有什么区别?

未注册的 HTML 自定义元素和注册的 HTML 自定义元素有什么区别?

qq_遁去的一_1 2023-08-24 10:05:06
如果我无法注册自定义元素,我注意到我仍然可以:使用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-1myRegisteredCustomElement1


查看完整回答
反对 回复 2023-08-24
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信