【问题标题】:getComputedStyle returns a CSSStyleDeclaration but all properties are empty on accessgetComputedStyle 返回一个 CSSStyleDeclaration 但所有属性在访问时都是空的
【发布时间】:2016-02-16 20:01:00
【问题描述】:

我有一个简单的 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)"

【问题讨论】:

  • 你能在 JSFiddle 或 CodePen 中复制这个问题吗?
  • 谢谢@swider。今天第一次和 JSFiddle 坐下来,结果我找到了解决办法。

标签: css properties getcomputedstyle


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2020-02-25
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多