4

我正在寻找学习如何使用更新的 HTML5 Web 组件规范扩展默认 HTML 元素。我在这里尝试了谷歌概述的示例: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 以不同的顺序放置,并在示例中将 HTMLImageElement 换成 Image。任何帮助将不胜感激!

4

1 回答 1

3

这是因为自定义的内置元素尚未在 Chrome / Opera 中实现。在这个问题中检查 Chromium 开发者的状态。

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

同时你应该使用像WebReflection's one这样的 polyfill 。

自 Chrome 67 以来的更新

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

于 2016-12-10T00:07:57.457 回答