function getClassTree(dom) {
const spaceCount = 2; // 缩进空格数
const ignore = 'ng-'; // 忽略类名
const preset = [ // 预设样式
'font-size: unset'
];
if (typeof dom === 'string') {
dom = document.querySelector(dom);
}
const tree = {};
function getTree(parent, node) {
if (node) {
let child = {
$$preset: preset
};
let name = '';
let classList = [];
if (node.classList && node.classList.length > 0) {
classList = Array.from(node.classList).filter(function (o) {
return o.indexOf(ignore) === -1;
});
}
if (classList.length > 0) {
name = '.' + classList.join(', .');
} else if (node.id) {
name = '#' + node.id;
} else if (node.tagName) {
name = node.tagName;
} else {
name = '*';
}
if (node.children && node.children.length > 0) {
Array.from(node.children).forEach(function (n) {
getTree(child, n);
});
}
if (parent[name]) {
Object.assign(parent[name], child);
} else {
parent[name] = child;
}
}
}
getTree(tree, dom);
function getTreeCss(obj, index) {
const space = spaceCount ? new Array(index).join(new Array(spaceCount + 1).join(' ')) : '';
let result = '';
if (obj) {
Object.keys(obj).forEach(function (k) {
if (k === '$$preset') {
result += `${space}${obj.$$preset.join(`;\n${space}`)};`;
} else {
result += `\n\n${space}${k} {
${getTreeCss(obj[k], index + 1)}
${space}}\n`;
}
});
}
return result;
}
const text = getTreeCss(tree, 1);
const input = document.createElement('textarea');
input.value = text;
document.body.appendChild(input);
input.select();
input.setSelectionRange(0, input.value.length);
document.execCommand('Copy');
document.body.removeChild(input);
return text;
}
将DOM提取为Less样式
最新推荐文章于 2022-07-05 16:53:07 发布
本文介绍了一个用于生成DOM元素样式树的JavaScript函数,该函数能递归遍历DOM树并收集所有非预设的类样式,最终以CSS形式输出,便于开发者快速获取页面样式结构。
2296

被折叠的 条评论
为什么被折叠?



