Bac*_*ash 4 html javascript parsing domparser
我正在尝试获取使用 DOMParser 解析的元素的样式属性。不过,2 个 console.log 都是空的。知道为什么会发生这种情况吗?
<div id='foobar'>
<style>
.xl496
{
color:#336699;
}
</style>
<table>
<tr>
<td class='xl496'>Test:</td>
</tr>
</table>
</div>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
<div id='foobar'>
<style>
.xl496 {
color: #336699;
}
</style>
<table>
<tr>
<td class='xl496'>Test:</td>
</tr>
</table>
</div>Run Code Online (Sandbox Code Playgroud)
您可以使用此答案中的内容查看将 RGB 转换为 HEX 的解决方案