我正在构建 Web 组件并且一切正常,但是当我尝试获取元素的宽度时遇到了这个问题,它记录了我
Cannot read property 'getBoundingClientRect' of null
下面一行记录实际宽度。
我的代码:
attributeChangedCallback(name, oldVal, newVal) {
const innerBar = this.shadow.querySelector('.progress-name-inner');
const progressTitle = this.shadow.querySelector('.progress-title');
console.log(progressTitle.getBoundingClientRect().width)
switch (name) {
case 'title':
this._title = newVal || '';
break;
case 'complete':
this._complete = parseInt(newVal) || 0;
innerBar.style.width = this.complete + '%'
break;
}
}
最佳答案
当内联定义 HTML 元素属性时(在 HTML 代码中),attributeChangedCallback()
方法在 connectedCallback()
方法之前被调用。
因此,如果要处理自定义元素属性,最好在 constructor()
方法中设置 Shadow DOM HTML 内容。
此外,当异常被抛出时,方法执行停止,这就是 innerBar.style.width
上的错误没有被抛出的原因。
关于javascript - 在 shadow dom 中选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52466388/