0

我正在尝试获取页面上所有 p 元素的文本颜色和背景颜色:

elements = document.querySelectorAll("p");
console.log("elements " + elements.length);
console.log(window.getComputedStyle(elements[0]));
console.log(window.getComputedStyle(elements[0]).length);
console.log(window.getComputedStyle(elements[0]).getPropertyValue("background-color"));
console.log(window.getComputedStyle(elements[0]).getPropertyValue("color"));
console.log(elements[0].innerHTML);

这打印:

background-color: rgba(0, 0, 0, 0)
color: rgb(225, 224, 220)

但是,如果我继续使用 chrome 并检查第一个 p 元素计算样式,它会显示:

background-color: #43413e (67, 65, 62 as rgb)
color: #e1e0dc (225, 224, 220 as rgb)

这应该让我获得“计算”风格,那么为什么不这样做呢?我在这里想念什么?它应该打印brackground-color: rgb(67, 65, 62)

4

1 回答 1

0

我不确定您在哪里运行此代码,但我预计样式正在以编程方式进行更改。问题很可能是您在更改发生后在 chrome 中手动检查该值,但 phantomJS 过早地检查该值。也许将您的控制台日志放入一个函数中,并延迟执行该函数(例如使用setTimeout)将解决问题。

于 2016-11-09T13:29:45.850 回答