我试图获得一个元素的样式属性,并使用DOMParser进行解析。然而,2 console.logs却是空的。知道为什么会这样吗?
<div id='foobar'>
<style>
.xl496
{
color:#336699;
}
</style>
<table>
<tr>
<td class='xl496'>Test:</td>
</tr>
</table>
</div>var data = document.getElementById("foobar");
var parser = new DOMParser();
var doc = parser.parseFromString(data.innerHTML, "text/html");
var cols = doc.getElementsByTagName("tr");
var col = cols[0];
var tds = col.getElementsByTagName("td");
var td = tds[0];
console.log(getComputedStyle(td).getPropertyValue("color"));
console.log(td.style.color);发布于 2016-08-03 14:47:22
getComputedStyle是一个只对窗口可用的方法。因为代码在DOM解析器中,所以它没有正确的上下文,因此在调用中返回空字符串。所以,这里有个绕过它的方法。您可以将有问题的元素插入窗口,运行getComputedStyle,然后将其放入DOMParser (片段)中。
var clipboardData = document.getElementById("foobar").outerHTML;
var parser = new DOMParser();
var doc = parser.parseFromString(clipboardData, "text/html");
var col = doc.querySelector("tr");
var td = col.querySelector("td");
// td has to be in the window, not a fragment in order to use window.getComputedStyle
document.body.appendChild(td);
console.log(window.getComputedStyle(td).getPropertyValue("color"));
// the next one expected to be "" since it does not have inline styles
console.log(td.style.color);
// Insert the td back into the dom parser where it was
col.insertBefore(td, col.firstChild);<div id='foobar'>
<style>
.xl496 {
color: #336699;
}
</style>
<table>
<tr>
<td class='xl496'>Test:</td>
</tr>
</table>
</div>
您可以使用this answer中的内容查看将RGB转换为HEX的解决方案。
https://stackoverflow.com/questions/38746442
复制相似问题