简体   繁体   English

在 shadow dom 中选择元素

[英]Selecting element within shadow dom

I'm building web component and it's all going fine, but I have this problem when I try to get width of element and it logs me我正在构建 Web 组件并且一切正常,但是当我尝试获取元素的宽度并且它记录我时遇到了这个问题

Cannot read property 'getBoundingClientRect' of null无法读取 null 的属性“getBoundingClientRect”

and line bellow that it logs actual width.和下面的一行,它记录了实际宽度。

My code:我的代码:

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;
    }
}

When an HTML element attribute is defined inline (in the HTML code), the attributeChangedCallback() method is called before the connectedCallback() method.当内联(在 HTML 代码中)定义 HTML 元素属性时,将在connectedCallback()方法之前调用attributeChangedCallback() connectedCallback()方法。

So you'd better set the Shadow DOM HTML content in the constructor() method if you want to process Custom Elements attributes.所以如果要处理自定义元素属性,最好在constructor()方法中设置Shadow DOM HTML内容。

Also, when an exception is thrown the method excution stops, that's why the error on innerBar.style.width is not thrown.此外,当抛出异常时,方法执行停止,这就是不抛出关于innerBar.style.width的错误的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM