Custom Elements详解

        自定义元素为作者构建自己的完整功能DOM元素提供了一种方法。虽然作者总是可以在他们的文档中使用非标准元素,但通过脚本编写或类似方法添加特定于应用程序的行为后,这些元素在历史上一直不符合要求,而且功能也不是很强大。通过定义自定义元素,作者可以通知解析器如何正确构建元素以及该类的元素如何对变化作出反应。

一、创建一个自定义元素

        我们想要创建一个为了说明如何创建自主自定义元素,我们定义一个自定义元素,该元素封装为国家/地区标志呈现小图标。我们的目标是能够像这样使用它:

<flag-icon country="nl"></flag-icon>
为此,我们首先为自定义元素声明一个类,并扩展 HTMLElement
class FlagIcon extends HTMLElement {
  constructor() {
    super();
    this._countryCode = null;
  }

  static get observedAttributes() { return ["country"]; }

  attributeChangedCallback(name, oldValue, newValue) {
    // name will always be "country" due to observedAttributes
    this._countryCode = newValue;
    this._updateRendering();
  }
  connectedCallback() {
    this._updateRendering();
  }

  get country() {
    return this._countryCode;
  }
  set country(v) {
    this.setAttribute("country", v);
  }

  _updateRendering() {
    // Left as an exercise for the reader. But, you'll probably want to
    // check this.ownerDocument.defaultView to see if we've been
    // inserted into a document with a browsing context, and avoid
    // doing any work if not.
  }
}
customElements .define(“ flag-icon ”,FlagIcon);

使用方法

在html中直接使用

<flag-icon country="nl"></flag-icon>

使用js添加

const flagIcon = document.createElement("flag-icon")
flagIcon.country = "jp"
document.body.appendChild(flagIcon)


const flagIcon = new FlagIcon()
flagIcon.country = "jp"
document.body.appendChild(flagIcon)

二、创建一个定制的内置元素

class PlasticButton extends HTMLButtonElement {
  constructor() {
    super();

    this.addEventListener("click", () => {
      alert('hello world')
    });
  }
}
customElements.define("button-hello", PlasticButton, { extends: "button" });


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值