javascript - 如何在javascript中将rgb颜色转换为颜色名称字符串
问题描述
如何在javascript中将rgb颜色转换为颜色名称字符串
let btn = document.querySelector("#demo");
let css = getComputedStyle(btn);
console.log(css.color);
输出为 rgb 值 rgb(255,0,0)
解决方案
您需要将 RGB 字符串转换为十六进制值,然后您可以将其与HTML 颜色名称列表进行比较。
const colors={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff"};
// Pass in the string
function toHex(rgb) {
// Grab the numbers
const match = rgb.match(/\d+/g);
// `map` over each number and return its hex
// equivalent making sure to `join` the array up
// and attaching a `#` to the beginning of the string
return `#${match.map(color => {
const hex = Number(color).toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}).join('')}`;
}
// Now just iterate over the colors object and return the
// key from the property where the value matches the hex value
function findColor(hex) {
const pair = Object.entries(colors).find(([key, value]) => {
return value === hex;
});
return pair[0];
}
const hex1 = toHex('rgb(255, 228, 196)');
console.log(findColor(hex1));
const hex2 = toHex('rgb(127, 255, 212)');
console.log(findColor(hex2));
推荐阅读
- c# - 使用键盘上的标签按钮时,标签页不会获得焦点
- javascript - 不能在类组件中调用 React Hook “useState”。必须在 React 函数组件或自定义 React Hook 函数中调用 React Hooks
- android - 如何在kotlin中通过retrofit2获取json
- javascript - 反应原生 | 动态变量
- c# - C# 合并值相同的单元格
- laravel - Browsershot:每张纸显示两页
- python - Multiple groupings and aggregations within one dataframe using Python
- mysql - 如何在更新前验证数量是否存在
- r - 在颜色矩阵中转换非方阵?
- vb.net - 比较数据库字段中的值并检查是否与VB中的变量相同