[英]How can I get rgb (or hex) code from css color-name in javascript?
I am making a canvas gauge plugin and I need to convert css color codes like 'pink' and 'orange' into RGB format.我正在制作一个画布仪表插件,我需要将诸如“粉红色”和“橙色”之类的 css 颜色代码转换为 RGB 格式。
I thought of setting some element to background: pink;
我想为background: pink;
and the getting that color back with $('el').css('background');
并使用$('el').css('background');
恢复该颜色like this but I don't know if that would always return what i want and it seems weird anyway.像这样,但我不知道这是否总是会返回我想要的东西,而且看起来很奇怪。
I am hoping there is some built in window method or something that can do this conversion for me without me having to include a big map-object for all the codes.我希望有一些内置的窗口方法或可以为我做这种转换的东西,而不必为所有代码包含一个大的地图对象。
github.com/jquery/jquery-color/blob/master/jquery.color.js
可能是您所追求的处理库。
I need to convert css color codes like 'pink' and 'orange' into RGB format [...] I am hoping there is some built in window method or something that can do this conversion for me without me having to include a big map-object for all the codes.我需要将诸如“粉红色”和“橙色”之类的 CSS 颜色代码转换为 RGB 格式 [...] 我希望有一些内置的窗口方法或可以为我进行此转换的东西,而无需包含大地图-所有代码的对象。
Yes, there is.就在这里。 The method you are looking for is window.getComputedStyle()
您正在寻找的方法是window.getComputedStyle()
You can run through the following steps:您可以执行以下步骤:
<div>
创建一个标准<div>
<div>
将颜色添加到<div>
的样式对象<div>
to the DOM将<div>
附加到DOMwindow.getComputedStyle()
to inspect the computed styles of the <div>
使用window.getComputedStyle()
来检查<div>
的计算样式Working Example:工作示例:
const colorKeywordToRGB = (colorKeyword) => { // CREATE TEMPORARY ELEMENT let el = document.createElement('div'); // APPLY COLOR TO TEMPORARY ELEMENT el.style.color = colorKeyword; // APPEND TEMPORARY ELEMENT document.body.appendChild(el); // RESOLVE COLOR AS RGB() VALUE let rgbValue = window.getComputedStyle(el).color; // REMOVE TEMPORARY ELEMENT document.body.removeChild(el); return rgbValue; } console.log('pink:', colorKeywordToRGB('pink')); console.log('orange:', colorKeywordToRGB('orange'));
Further Reading:延伸阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.