自定义元素为作者提供了一种构建他们自己的全功能 DOM 元素的方法。尽管作者总是可以在他们的文档中使用非标准元素,并在事后通过脚本或类似方式添加特定于应用程序的行为,但这些元素历来不符合标准且功能不强。通过定义自定义元素,作者可以通知解析器如何正确构造元素以及该类的元素应如何对更改做出反应。
自定义元素是“使平台合理化”的更大努力的一部分,通过根据较低级别的作者公开的可扩展性点(如自定义元素定义)解释现有平台功能(如 HTML 元素)。尽管今天自定义元素的功能存在许多限制——无论是功能上还是语义上——阻止它们完全解释 HTML 现有元素的行为,但我们希望随着时间的推移缩小这种差距。
看个具体的例子。
<!DOCTYPE html> <html lang="en"> <body> <flag-icon country="in"></flag-icon><br> <flag-icon country="nl"></flag-icon><br> <flag-icon country="us"></flag-icon><br> </body> <script> class FlagIcon extends HTMLElement { constructor() { super(); this._countryCode = null; } static observedAttributes = ["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() { //**remaining code** if (this.ownerDocument.defaultView && !this.hasChildNodes()) { var flag = document.createElement("img"); flag.src = "https://flagcdn.com/24x18/" + this._countryCode + ".png"; this.appendChild(flag); } } } customElements.define("flag-icon", FlagIcon); </script> </html>