从css中提取颜色

问题描述 投票:0回答:3

我需要从 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 颜色吗?

谢谢你。

javascript jquery css colors
3个回答
0
投票

任何…用于提取并显示十六进制和 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);


0
投票

您可以使用

window.getComputedStyle()

从元素中获取所有样式 示例:

let element = document.querySelector('.class');

let styles = window.getComputedStyle(element);

导航器控制台中的实验是支持像 Chrome 和 Firefox 这样的 JavaScript。

获取页面任意元素,探索

.getComputedStyle(...)
函数属性。

  • getCompulatedStyle 只需提供 rgb。

另一种方法,是使用函数转换来转换为你这样的:

https://www.phpied.com/rgb-color-parser-in-javascript/


0
投票

你尝试过“;”吗?在 rgb 和 rgba 值的括号之后?这就是我在 Oracle Apex 中将其内联到 CSS 中的方式。

© www.soinside.com 2019 - 2024. All rights reserved.