javascript - 从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 颜色?
谢谢你。
解决方案
任何...用于提取和显示十六进制和 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);
推荐阅读
- vue.js - 在我导航到另一个产品页面之前没有显示对话框
- c++ - OpenGL 对象在屏幕空间中拖动后变形
- python-3.x - 将科学记数法从 decimal.Decimal 抑制为 String
- jquery - 使用 jquery 将数组或列表发送到 asp.net mvc 控制器
- database - 有序索引与聚集索引
- php - “WC_Abstract_Legacy_Order->__get, wc_doing_it_wrong” WooCommerce 错误
- javascript - 处理 ember 和 rails 中的验证错误
- azure - 交换 Azure webapp 部署槽时,并非所有流量都进入生产
- notepad++ - 删除记事本++中两个字符串之间的特定字符串
- django - Django 强制 Python3