13

我有一个简单的 div,它使用一个 css 类,该类又具有一个colorbackground-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"));

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

4

1 回答 1

10

最终的问题getComputedStyle是,有问题的元素似乎必须是 DOMTree 的一部分,才能使任何样式可用。

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

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

所以基本上,我将我的更改container.appendChilddocument.body.appendChild临时以立即计算我需要的样式,然后将其删除并销毁它,只留下我需要的颜色。

于 2016-02-16T12:01:00.763 回答