define() 方法在 CustomElementRegistry interface defines a new custom element.

There are two types of custom elements you can create:

  • Autonomous custom element : Standalone elements; they don't inherit from built-in HTML elements.
  • Customized built-in element : These elements inherit from — and extend — built-in HTML elements.

句法

customElements.define(name, constructor, options);
					

参数

名称

Name for the new custom element. Note that custom element names must contain a hyphen.

构造函数

Constructor for the new custom element.

选项 可选
Object that controls how the element is defined. One option is currently supported:
  • extends : String specifying the name of a built-in element to extend. Used to create a customized built-in element .

返回值

Void.

异常

异常 描述
NotSupportedError CustomElementRegistry already contains an entry with the same name or the same constructor (or is otherwise already defined), or extends is specified and it is a valid custom element name ,或 extends is specified but the element it is trying to extend is an unknown element.
SyntaxError The provided name is not a valid custom element name .
TypeError The referenced constructor is not a constructor.

注意 : You'll often get NotSupportedError s thrown that seem like define() is failing, but instead it is likely a problem with Element.attachShadow() .

范例

Autonomous custom element

The following code is taken from our popup-info-box-web-component example ( see it live also ).

// Create a class for the element
class PopUpInfo extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();
    // Create a shadow root
    var shadow = this.attachShadow({mode: 'open'});
    // Create spans
    var wrapper = document.createElement('span');
    wrapper.setAttribute('class','wrapper');
    var icon = document.createElement('span');
    icon.setAttribute('class','icon');
    icon.setAttribute('tabindex', 0);
    var info = document.createElement('span');
    info.setAttribute('class','info');
    // Take attribute content and put it inside the info span
    var text = this.getAttribute('text');
    info.textContent = text;
    // Insert icon
    var imgUrl;
    if(this.hasAttribute('img')) {
      imgUrl = this.getAttribute('img');
    } else {
      imgUrl = 'img/default.png';
    }
    var img = document.createElement('img');
    img.src = imgUrl;
    icon.appendChild(img);
    // Create some CSS to apply to the shadow dom
    var style = document.createElement('style');
    style.textContent = '.wrapper {' +
                           'position: relative;' +
                        '}' +
                         '.info {' +
                            'font-size: 0.8rem;' +
                            'width: 200px;' +
                            'display: inline-block;' +
                            'border: 1px solid black;' +
                            'padding: 10px;' +
                            'background: white;' +
                            'border-radius: 10px;' +
                            'opacity: 0;' +
                            'transition: 0.6s all;' +
                            'position: absolute;' +
                            'bottom: 20px;' +
                            'left: 10px;' +
                            'z-index: 3;' +
                          '}' +
                          'img {' +
                            'width: 1.2rem' +
                          '}' +
                          '.icon:hover + .info, .icon:focus + .info {' +
                            'opacity: 1;' +
                          '}';
    // attach the created elements to the shadow dom
    shadow.appendChild(style);
    shadow.appendChild(wrapper);
    wrapper.appendChild(icon);
    wrapper.appendChild(info);
  }
}
// Define the new element
customElements.define('popup-info', PopUpInfo);
					
<popup-info img="img/alt.png" text="Your card validation code (CVC) is an extra
                                    security feature — it is the last 3 or 4
                                    numbers on the back of your card.">
					

注意 : Constructors for autonomous custom elements must extend HTMLElement .

Customized built-in element

The following code is taken from our word-count-web-component example ( see it live also ).

// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();
    // count words in element's parent element
    var wcParent = this.parentNode;
    function countWords(node){
      var text = node.innerText || node.textContent
      return text.split(/\s+/g).length;
    }
    var count = 'Words: ' + countWords(wcParent);
    // Create a shadow root
    var shadow = this.attachShadow({mode: 'open'});
    // Create text node and add word count to it
    var text = document.createElement('span');
    text.textContent = count;
    // Append it to the shadow root
    shadow.appendChild(text);
    // Update count when element content changes
    setInterval(function() {
      var count = 'Words: ' + countWords(wcParent);
      text.textContent = count;
    }, 200)
  }
}
// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });
					
<p is="word-count"></p>
					

规范

规范 状态 注释
HTML 实时标准
The definition of 'customElements.define()' in that specification.
实时标准 初始定义。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
define Chrome 66 注意事项
66 注意事项
Support for 'Customized built-in elements' as well.
54 注意事项
Support for 'Autonomous custom elements' only.
Edge 79 注意事项
79 注意事项
Support for 'Customized built-in elements' as well.
79 注意事项
Support for 'Autonomous custom elements' only.
Firefox 63
63
59 — 63 Disabled
Disabled From version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.customelements.enabled preference (needs to be set to true ). To change preferences in Firefox, visit about:config.
? — 59 Disabled
Disabled Until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to true ) 和 preference (needs to be set to ). To change preferences in Firefox, visit about:config.
IE 不支持 No Opera 53 注意事项
53 注意事项
Support for 'Customized built-in elements' as well.
41 注意事项
Support for 'Autonomous custom elements' only.
Safari 10.1 注意事项
10.1 注意事项
Supports 'Autonomous custom elements' but not 'Customized built-in elements'
WebView Android 66 注意事项
66 注意事项
Support for 'Customized built-in elements' as well.
54 注意事项
Support for 'Autonomous custom elements' only.
Chrome Android 66 注意事项
66 注意事项
Support for 'Customized built-in elements' as well.
54 注意事项
Support for 'Autonomous custom elements' only.
Firefox Android 63
63
59 — 63 Disabled
Disabled From version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.customelements.enabled preference (needs to be set to true ). To change preferences in Firefox, visit about:config.
? — 59 Disabled
Disabled Until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to true ) 和 preference (needs to be set to ). To change preferences in Firefox, visit about:config.
Opera Android 47 注意事项
47 注意事项
Support for 'Customized built-in elements' as well.
41 注意事项
Support for 'Autonomous custom elements' only.
Safari iOS 10.3 注意事项
10.3 注意事项
Supports 'Autonomous custom elements' but not 'Customized built-in elements'
Samsung Internet Android 9.0 注意事项
9.0 注意事项
Support for 'Customized built-in elements' as well.
6.0 注意事项
Support for 'Autonomous custom elements' only.

图例

完整支持

完整支持

不支持

不支持

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

见实现注意事项。

用户必须明确启用此特征。

用户必须明确启用此特征。

元数据

  • 最后修改:
  1. CustomElementRegistry
  2. 方法
    1. define()
    2. get()
    3. upgrade()
    4. whenDefined()

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1