【发布时间】:2021-08-16 13:54:29
【问题描述】:
我正在尝试将一个元素从 light DOM 移动到 shadow DOM,但是当我这样做时,样式不会被复制。我试图通过设置newElement.style = window.getComputedStyle(elem) 来解决这个问题,但这似乎不起作用。样式应该是:
.card {
color: #ff0;
font-size: 3rem;
font-weight: 600;
border: 3px solid blueviolet;
background-color: greenyellow;
}
但样式不适用,当我打印 getComputedStyle() 以控制台时,我看到的是:
all the values are empty
但是,当我像这样循环使用 getComputedStyle() 和 .getPropertyValue() 的属性时:
for(let property of style){
console.log(`property: ${property}, value: ${style.getPropertyValue(property)}`);
}
我在控制台中得到的是: the correct values
所以我很困惑为什么getComputedStyle() 不包含这些值,但使用getComputedStyle().getPropertyValue() 会返回正确的值。我确定我遗漏了一些明显的东西,因为我在任何地方都找不到关于此的其他帖子。
任何帮助将不胜感激,在此先感谢。
编辑:我采用了下面 Danny 提供的代码并对其进行了修改,以更好地显示我面临的问题:
<style>
.card {
color: yellow;
background: green;
}
</style>
<my-element>
<div class="card">lightDOM reflected to shadowDOM</div>
</my-element>
<script>
customElements.define("my-element", class extends HTMLElement {
constructor(){
super().attachShadow({mode:"open"}).innerHTML = ``;
}
connectedCallback() {
setTimeout(() => { // wait till innerHTML is parsed
let card = this.children[0]; // Get the light DOM Card element
this.shadowRoot.appendChild(card.cloneNode(true)); // Append it to the shadowDOM
let style = window.getComputedStyle(card); // Get style of the Light DOM Card
this.shadowRoot.querySelector('.card').style = style; // Set the ShadowDOM card style equal to the Light DOM Style
console.log(style);
console.log(style.color); // yellow = rgb:255,255,0
console.log(style.background); // green = rgb:0,128,0
card.remove(); // Remove the card from the Light DOM to prevent duplication
})
}
})
</script>
请注意,上面的样式并不适用,即使它似乎与文档指定的完全一样: "返回的对象与从元素的 style 属性返回的对象的 CSSStyleDeclaration 类型相同。但是,这两个对象有不同的用途:
- getComputedStyle 中的对象是只读的,应用于检查元素的样式——包括由元素或外部样式表设置的样式。
- 应使用 element.style 对象在该元素上设置样式,或检查通过 JavaScript 操作或全局样式属性直接添加到该元素的样式。” https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle#description
【问题讨论】:
-
全局 CSS 不设置 shadowDOM 的样式,这是 shadowDOM 的主要用途。如果您在 DOM 中有单独的样式标签,您可以将其移动或复制到 shadowDOM
-
@Danny'365CSI'Engelman “您可以将其移动或复制到 shadowDOM”,是的,我正在尝试这样做,但以编程方式而不是手动方式。这就是我遇到的问题,即轻型 DOM 元素的
getComputedStyle()由于某种原因为空白
标签: javascript css web web-component