- 使用customElements.define()方法创建,方法传递两个参数,第一个自定义元素名字,第二个HTMLElement扩展子类
- 浏览器自动调用自定义元素的‘生命期方法’,当自定义元素插入文档时会调用connectedCallback()方法。还有一个disconnectedCallback()方法 在元素从文档中移除时调用,但用的不多
- 定义静态属性observedAttributes,其值是一个属性名数组,当元素使用其定义的属性名,浏览器会调用attributeChangedCallback()方法,该方法传入属性名、旧值、新值。
- 定义js获取元素属性和修改元素属性方法,让元素暴露为js属性
customElements.define('inline-circle', class InlineCircle extends HTMLElement {
connectedCallback() {
this.style.display = 'inline-block'
this.style.border = '1px solid black'
this.style.borderRadius = '50%'
this.style.transform = 'translateY(10%)'
if (!this.style.width) {
this.style.width = '.8em'
this.style.height = '.8em'
}
}
static get observedAttributes() { return ['diameter', 'color'] }
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case 'diameter':
this.style.width = newValue
this.style.height = newValue
break
case 'color':
this.style.backgroundColor = newValue
break
}
}
get diameter() { return this.getAttribute('diameter') }
set diameter(diameter) { return this.setAttribute('diameter', diameter) }
get color() { return this.getAttribute('color') }
set color(color) { return this.setAttribute('color', color) }
})