DOMParser - 获取元素样式

4
我试图获取使用DOMParser解析的元素的样式属性。但是两个console.log都没有输出任何内容。不知道这是为什么?
<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);

你必须使用DOMParser吗? - KevBot
1
是的。因为我计划后来从剪贴板获取这样的数据:e.clipboardData.getData('text/html'); - Backslash
1个回答

7

getComputedStyle是一种仅适用于窗口的方法。由于您的代码位于DOM解析器内部,因此它没有正确的上下文,并且在调用中返回空字符串。因此,以下是一个解决方法。您可以取出相关元素,将其插入到窗口中,运行getComputedStyle,然后将其放回DOM解析器(片段)。

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>

您可以查看此答案中提供的解决方案,将RGB转换为HEX。

当然可以。但我计划将剪贴板集成作为下一步。那么我将从e.clipboardData.getData('text/html'); 获取数据。 - Backslash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接