首页 > 解决方案 > 如何使用 getComputedStyle 将 HTML 子树转换为字符串和内联样式?

问题描述

我需要将网站的一部分转换为带有从 getComputedStyle 生成的内联 CSS 的 html 字符串。

这个想法是将所有嵌套和平面元素转换为具有内联样式的字符串。输出可以粘贴到 .html 或在线代码编辑器中,并且看起来相同。它接近了,我已经修补了一个小时左右。

到目前为止,这是我的代码:

function loopThroughRoots(root) {
    let htmlString = "";
    let temp = root;

    console.log(root.tagName);

    temp.setAttribute(
        "style",
        window.getComputedStyle(root).cssText
    );

    if (temp.children.length > 0) {
        console.log("has children, looping");
        for (let i = 0; i < temp.children.length; i++) {
            htmlString += loopThroughRoots(temp.children[i]);
        }
    } else {
        console.log("no children, setting value");
        htmlString = temp.outerHTML;
    }

    return htmlString;
}

var root = document.querySelector("#markdown");
console.log(loopThroughRoots(root));

但它似乎错过了任何有孩子的元素。这些父标签(及其样式)不会出现在最终字符串中。

我可以更改哪些以包含这些父元素?或者我还能怎么做?

这是一个例子:

示例笔

标签: javascriptcssdom

解决方案


我可以通过将父节点的 innerHTML 设置为字符串、循环子节点而不是子节点以及处理文本节点来修复它。

function loopThroughRoots(root) {
  let htmlString = "";
  let temp = root.cloneNode(true);

  //if text
  if (temp.nodeType == 3) {
    return temp.nodeValue;
  }

  //normal node with children
  if (temp.nodeType == 1) {
    if (temp.nodeType == 1 && temp.childNodes && temp.childNodes.length > 0) {
      for (let i = 0; i < temp.childNodes.length; i++) {
        htmlString += loopThroughRoots(temp.childNodes[i]);
      }
      temp.innerHTML = htmlString;
      temp.setAttribute("style", window.getComputedStyle(root).cssText);
      htmlString = temp.outerHTML;
    } else {
      //normal node, no children
      temp.setAttribute("style", window.getComputedStyle(root).cssText);
      htmlString = temp.outerHTML;
    }
  }
  return htmlString;
}

function runTest() {
  var root = document.querySelector("#example");
  console.log(loopThroughRoots(root));
}

演示:https ://codepen.io/ethan-vernon/pen/OJVQxXL?editors=1010


推荐阅读