本文介绍了尽管打开,ShadowRoot 属性为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问元素上的 ShadowRoot,并且属性 element.shadowRoot 正在返回 null.
ShadowDOM 定义为 mode: 'open',这是正确的,我什至可以 console.log(element) 看到所有properties 和 shadowRootShadowRoot 类型的对象.

I'm trying to access the ShadowRoot on my element and the property element.shadowRoot is returning null.
The ShadowDOM is defined as mode: 'open', which is correct, I can even console.log(element) to see all of the properties and shadowRoot IS an object of ShadowRoot type.

在我的应用程序中,我试图像这样访问该属性:

In my app I am trying to access the property like so:

let el = document.getElementById('elementId');
...
console.log(el);
console.log("this.shadowRoot = ???");
console.log(el.shadowRoot);

这样好吗?

附件是控制台的 console.log() 输出,如您所见,shadowRoot 肯定存在.
(来自 Firefox 控制台)

Attached are the console.log() output from the console, as you can see the shadowRoot definitely is there.
(From the Firefox console)

我在最新的 Firefox 和 Chrome 中都尝试过,结果都一样.
我做错了什么?

I have tried in both latest Firefox and Chrome, both have same result.
What am I doing wrong?

谢谢

编辑

我创建了一个小 JSFiddle.
如果您按 F12 并查看控制台,您可以看到该元素已记录并显示 shadowRoot 属性,但记录 shadowRoot 显示 >null.

I have created a little JSFiddle.
If you press F12 and view the console you can see that the element is logged and shows the shadowRoot property, but logging the shadowRoot displays null.

我想知道这是否是一个错误?也许它还没有完全实施?

I wonder if this is a bug? Perhaps it is not fully implemented yet?

我已经看到 firefox 中的 Element.shadowRoot 但我使用的是最新的 (65)Firefox 和 (72) Chrome.

I have seen Element.shadowRoot in firefox but I am using the latest (65) of Firefox and (72) Chrome.

推荐答案

注意脚本执行顺序.

在您的示例中,您试图在定义自定义元素之前获取 shadowRoot 属性.

In your example you are trying to get the shadowRoot propery before the Custom Element is defined.

当你在正确的时间获得价值时它会起作用.

您可以使用 whenDefined() 方法来确保元素已定义:

You could use the whenDefined() method to be sure the element is defined:

customElements.whenDefined( 'web-component ').then( () => {
    let el = document.getElementById('elementId');
    console.log(el.shadowRoot);
} )

这篇关于尽管打开,ShadowRoot 属性为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 00:05