我需要从 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 颜色吗?
谢谢你。
任何…用于提取并显示十六进制和 rgb/gba 颜色的 javascript [从 CSS 文件]?
您可以使用 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);
您可以使用
window.getComputedStyle()
let element = document.querySelector('.class');
let styles = window.getComputedStyle(element);
导航器控制台中的实验是支持像 Chrome 和 Firefox 这样的 JavaScript。
获取页面任意元素,探索
.getComputedStyle(...)
函数属性。
另一种方法,是使用函数转换来转换为你这样的:
你尝试过“;”吗?在 rgb 和 rgba 值的括号之后?这就是我在 Oracle Apex 中将其内联到 CSS 中的方式。