getComputedStyle返回CSSStyleDeclaration,但访问时所有属性均为空

getComputedStyle返回CSSStyleDeclaration,但访问时所有属性均为空,css,properties,getcomputedstyle,Css,Properties,Getcomputedstyle,我有一个简单的div,它使用一个css类,该类又有一个color和background color属性集 var div = document.createElement("div"); div.classList.add("my-css-class"); container.appendChild(div); //This prints out a CSSStyleDeclaration object. This is a large object to which I see `color

我有一个简单的div,它使用一个css类,该类又有一个
color
background color
属性集

var div = document.createElement("div");
div.classList.add("my-css-class");
container.appendChild(div);

//This prints out a CSSStyleDeclaration object. This is a large object to which I see `color` and `backgroundColor`
console.log(getComputedStyle(div));

//this gives me an empty string
console.log(getComputedStyle(div).color);

//this gives me an empty string
console.log(getComputedStyle(div).getPropertyValue("color"));

为什么我无法访问cssstyle声明的属性?我从第一份日志就知道了。我可以看到
color:“rgb(82194145)”

最终
getComputedStyle
的问题在于,要使任何样式可用,所讨论的元素必须是DOMTree的一部分

注意,在我的例子中,我将div添加到父容器中,但是,实例化点处的父容器尚未添加到DOMTree中

我没有使用
JSON.stringify()
打印该对象,这意味着稍后会出现值,但在访问时,这些值是空白的


因此,基本上,我将我的
容器.appendChild
临时更改为
文档.body.appendChild
,以立即计算我需要的样式,然后删除并销毁它,只留下我需要的颜色

你能在JSFIDLE或CodePen中复制这个问题吗?谢谢@swider。今天我第一次坐下来讨论JSFIDLE,结果找到了解决方案。