如何将默认HTML元素扩展为"定制的内置元素"使用Web组件?

时间:2016-12-09 21:40:28

标签: javascript html web-component custom-element google-web-component

我希望学习如何使用较新的HTML5 Web组件规范扩展默认HTML元素。我在这里尝试了Google概述的示例:https://developers.google.com/web/fundamentals/getting-started/primers/customelements

他们是:

匿名函数:

customElements.define('bigger-img', class extends Image {
  // Give img default size if users don't specify.
  constructor(width=50, height=50) {
    super(width * 10, height * 10);
  }
}, {extends: 'img'});
HTML中的

<img is="bigger-img" width="15" height="20">

命名功能:

// See https://html.spec.whatwg.org/multipage/indices.html#element-interfaces
// for the list of other DOM interfaces.
class FancyButton extends HTMLButtonElement {
  constructor() {
    super(); // always call super() first in the ctor.
    this.addEventListener('click', e => this.drawRipple(e.offsetX, e.offsetY));
  }

  // Material design ripple animation.
  drawRipple(x, y) {
    let div = document.createElement('div');
    div.classList.add('ripple');
    this.appendChild(div);
    div.style.top = `${y - div.clientHeight/2}px`;
    div.style.left = `${x - div.clientWidth/2}px`;
    div.style.backgroundColor = 'currentColor';
    div.classList.add('run');
    div.addEventListener('transitionend', e => div.remove());
  }
}

customElements.define('fancy-button', FancyButton, {extends: 'button'});
HTML中的

<button is="fancy-button" disabled>Fancy button!</button>

我无法让这些示例中的任何一个在Chrome 55中运行。创建自定义内置元素可能会起作用吗?我尝试以不同的顺序放置JS和HTML,并在示例中交换HTML的ImageImageElement。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

这是因为Chrome / Opera中尚未实现自定义内置元素。在https://developer.apple.com/library/content/samplecode/Speakerbox/Introduction/Intro.html中检查Chromium开发者的状态。

只有自主自定义元素已经在本地实现。

虽然你应该使用像this issue这样的polyfill。

自Chrome 67后更新

现在适用于Chrome 67及更高版本的版本。