1
我在尋找如何使用較新的HTML5 Web組件規範來擴展默認HTML元素。我曾嘗試通過谷歌在這裏列出的例子:https://developers.google.com/web/fundamentals/getting-started/primers/customelements如何使用Web組件將默認HTML元素擴展爲「自定義內置元素」?
它們是:
匿名函數:
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按不同順序排列,並在示例中將Image的HTMLImageElement替換掉。任何幫助將不勝感激!
能用'is =「花式按鈕」'語法進行一些操作嗎? – beatsforthemind