用楼上思想实现的:

const html = `

文字1

文字2 

文字3 

文字4

let div = document.createElement('div');

div.innerHTML = html;

function getData(node, data) {

if (!Array.isArray(data)) {

throw TypeError('data is not Array');

}

if (node.hasChildNodes()) {

node.childNodes.forEach(element => {

if (element.nodeType === 1) { // 元素结点

getData(element, data); // 递归

}

if (element.nodeType === 3) { // 文本结点

const text = element.nodeValue;

if (!text.match(/^\s*$/g)) { // 非空白字符

const style = element.parentNode.style; // 父节点样式

data.push({

text: text.trim(),

color: style.color,

font_size: style.fontSize,

});

}

}

});

}

}

let data = [];

getData(div, data);

console.log(data);

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐