javascript - 如何使用 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));
但它似乎错过了任何有孩子的元素。这些父标签(及其样式)不会出现在最终字符串中。
我可以更改哪些以包含这些父元素?或者我还能怎么做?
这是一个例子:
解决方案
我可以通过将父节点的 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
推荐阅读
- c++ - 方法模板 - 乘法定义 - 我做错了什么?
- ios - UITableView:找不到向上移动/对齐 tableIndex 元素的方法
- android - 如何使用 Android 代码更改分辨率(大小)和密度,Runtime.getRuntime().exec(...) 不起作用
- python - 两个 Django 查询集的联合不起作用
- c# - Selenium 中的 PageSource 属性可以在 JavaScript 加载数据时更新吗?
- c# - 列值是另一个值相同的另一列的最大值
- arrays - Mongodb $group + 数组项数
- java - JXPath:如何从地图中查询所有键
- r - 聚合具有特定共享值的行
- microsoft-cognitive - 将参数添加到 POST 分析方法