自定义元素为作者构建自己的完整功能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" });