此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Window.customElements

基线 广泛可用

自 2020年1月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

customElementsWindow 对象上的一个只读属性,接口返回一个 CustomElementRegistry 对象的引用,可用于注册新的 custom element,或者获取之前定义过的自定义元素的信息。

例子

这个属性最常用的例子是用来获取使用CustomElementRegistry.define()方法定义和注册的自定义元素,例如:

js
let customElementRegistry = window.customElements;
customElementRegistry.define("my-custom-element", MyCustomElement);

However, it is usually shortened to something like the following:

js
customElements.define(
  "element-details",
  class extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById(
        "element-details-template",
      ).content;
      const shadowRoot = this.attachShadow({ mode: "open" }).appendChild(
        template.cloneNode(true),
      );
    }
  },
);

参阅我们的 web-components-examples 获取更多有用的例子。

规范

规范
HTML
# dom-window-customelements

浏览器兼容性