【发布时间】:2020-06-22 19:56:29
【问题描述】:
我需要将网站的一部分转换为带有从 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));
但它似乎错过了任何有孩子的元素。这些父标签(及其样式)不会出现在最终字符串中。
我可以进行哪些更改以使这些父元素也包含在内?或者我还能怎么做?
这是一个例子:
【问题讨论】:
-
为什么不直接使用
root.innerHTML来获取html? -
我也需要计算样式作为内联样式
-
您可以使用stylesheets property 获取样式并将它们粘贴到目标中的
style元素中。
标签: javascript css dom