【发布时间】:2017-07-04 05:09:47
【问题描述】:
我正在尝试使用自定义元素 API 为游戏内浏览器引擎使用的自定义元素创建各种 polyfill,以显示按钮和类似内容。 但是,我似乎无法从构造函数中访问元素的属性(例如 src、href ...)。
这是一个例子:
class KWButton extends HTMLElement {
constructor() {
super();
var attributes = this.attributes;
var shadow = this.attachShadow({
mode: 'open'
});
var img = document.createElement('img');
img.alt = this.getAttribute('text'); // the getAttribute call returns null
img.src = this.getAttribute('src'); // as does this one
img.width = this.getAttribute('width'); // and this
img.height = this.getAttribute('height'); // and this
img.className = 'vivacity-kwbutton'; // this works fine
shadow.appendChild(img);
img.addEventListener('click', () => {
window.location = this.getAttribute('href'); // this works perfectly fine
});
}
}
customElements.define('kw-button',
KWButton);
<kw-button src="https://placekitten.com/g/198/39" width="198" height="39" icon_src="https://placekitten.com/g/34/32" icon_width="34" icon_height="32" href="https://placekitten.com/" text="placekiten" color="#ffffff" size="18"></kw-button>
【问题讨论】:
-
据我所知,这似乎工作正常。请注意,延迟
connectedCallback生命周期事件的工作(例如创建和加载图像)可能是明智的。 -
@lonesomeday 这很奇怪;它似乎没有在我的页面上运行 (vivacity.fs3d.net)
标签: javascript html custom-element