首页 > 解决方案 > 从css中提取颜色

问题描述

我需要从 CSS 中提取颜色。颜色有 3 种格式:

.style1 {
  color: #000;
}

.style2 {
  color: rgb(205, 92, 92)
}

.style3 {
  color: rgba(0, 0, 0, 0.5)
}

我有这个脚本(来自旧网页): https ://jsfiddle.net/fekula/54kcxu1a/5/

但我只获得十六进制颜色。rgb 和 rgba 未显示。

任何想法或一些类似的 javascript 用于提取和显示十六进制和 rgb/gba 颜色?

谢谢你。

标签: javascriptjquerycsscolors

解决方案


任何...用于提取和显示十六进制和 rgb/gba 颜色 [来自 CSS 文件] 的 javascript?

您可以使用String.prototype.matchAll()来定位 CSS 规则字符串中的所有 hex、rgb() 和 rgba() 实例。

const cssStr = `
.style1 {
  color: #000;
}

.style2 {
  color: rgb(205, 92, 92)
}

.style3 {
  color: rgba(0, 0, 0, 0.5)
}
`;

const regexHex = /#[A-Fa-f0-9]*/g;
const hexs = [...cssStr.matchAll(regexHex)].flat();
const regexRgb = /rgb\([0-9, ]*\)/g;
const rgbs = [...cssStr.matchAll(regexRgb)].flat();
const regexRgba = /rgba\([0-9, .]*\)/g;
const rgbas = [...cssStr.matchAll(regexRgba)].flat();
const colors = {
  hex: [...hexs],
  rgb: [...rgbs],
  rgba: [...rgbas]
};
console.log('colors:', colors);


推荐阅读