2016-02-12 37 views
5

我有一个简单的div使用一个css类,其中有一个colorbackground-color属性集。getComputedStyle返回一个CSSStyleDeclaration,但所有的属性都是空的访问

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")); 

为什么我无法访问CSSStyleDeclaration的属性?我知道这是从我的第一个日志。我可以看到color: "rgb(82, 194, 145)"

+0

您可以在JSFiddle或CodePen中复制问题吗? – swider

+1

谢谢@swider。我今天第一次和JSFiddle一起坐下,我找到了解决方案。 – Clark

回答

5

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

请注意,在我的情况下,我将div添加到父容器中,但是,实例化处的父容器尚未添加到DOMTree中。

我未能使用JSON.stringify()来打印对象,这意味着值稍后显示,但在访问时显示为空白。

因此,基本上,我将container.appendChild暂时更改为document.body.appendChild,以计算我需要的样式,然后将其删除并将其摧毁,只留下我需要的颜色。

相关问题