问题如下,当我在devtool或js代码中更新attr sticky时,我无法触发attributeChangedCallback。 _updateSticky()方法在滚动时运行得很好,添加和删除粘性attr。
class HeaderLogo extends HTMLElement {
static get observedAttribute() {
return ['alt-logo', 'sticky'];
}
constructor() {
super();
}
connectedCallback() {
this._updateSticky();
window.addEventListener('scroll', () => {
this._updateSticky();
}, false);
}
attributeChangedCallback(attrName, oldVal, newVal) {
console.log("attr changed");
}
/* evaluates if the logo should be in sticky state or not */
_updateSticky() {
let scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
let breakpoint = 50;
if (scrollTop > breakpoint) {
this.setAttribute('sticky', '');
} else {
this.removeAttribute('sticky');
}
}
}
window.customElements.define('header-logo', HeaderLogo);
答案 0 :(得分:4)
只是你有一个错字observedAttribute
应该是observedAttributes