使用以下jQuery代码可以获取元素背景色的RGB值:
$('#selector').css('backgroundColor');
有没有办法获取十六进制值而非RGB值?
使用以下jQuery代码可以获取元素背景色的RGB值:
$('#selector').css('backgroundColor');
有没有办法获取十六进制值而非RGB值?
我的精简版
//Function to convert rgb color to hex format
function rgb2hex(rgb) {
if(/^#/.test(rgb))return rgb;// if returns colors as hexadecimal
let re = /\d+/g;
let hex = x => (x >> 4).toString(16)+(x & 0xf).toString(16);
return "#"+hex(re.exec(rgb))+hex(re.exec(rgb))+hex(re.exec(rgb));
}
对于所有的函数式编程爱好者,这里提供一种略有函数式风格的方法 :)
const getHexColor = (rgbValue) =>
rgbValue.replace("rgb(", "").replace(")", "").split(",")
.map(colorValue => (colorValue > 15 ? "0" : "") + colorValue.toString(16))
.reduce((acc, hexValue) => acc + hexValue, "#")
const testRGB = "rgb(13,23,12)"
getHexColor(testRGB)
我正在使用Jasmine protractor,但是遇到了错误,例如- 预期 [ 'rgba(255, 255, 255, 1)' ] 包含 '#fff'。
以下函数对我很有用。
function RGBAToHexA(test:string) {
let sep = test.toString().indexOf(",") > -1 ? "," : " ";
const rgba = test.toString().substring(5).split(")")[0].split(sep);
console.log(rgba)
let r = (+rgba[0]).toString(16),
g = (+rgba[1]).toString(16),
b = (+rgba[2]).toString(16),
a = Math.round(+rgba[3] * 255).toString(16);
if (r.length == 1)
r = "0" + r;
if (g.length == 1)
g = "0" + g;
if (b.length == 1)
b = "0" + b;
if (a.length == 1)
a = "0" + a;
return "#" + r + g + b + a;
}
describe('Check CSS', function() {
it('should check css of login page', async function(){
browser.waitForAngularEnabled(true);
browser.actions().mouseMove(element(by.css('.btn-auth, .btn-auth:hover'))).perform(); // mouse hover on button
csspage.Loc_auth_btn.getCssValue('color').then(function(color){
console.log(RGBAToHexA(color))
expect( RGBAToHexA(color)).toContain(cssData.hoverauth.color);
})
*.padStart(2, "0")
替换 if (r.length == 1) ... r = "0" + r;
。 - Fabrice T嗨,这是我使用JavaScript获取元素颜色后得出的解决方案
function rgb_hex(rgb_string_js){ //example: "rgb(102,54,255)"
var new_rgb_list = rgb_string_js.replace("rgb(","").replace(")","").split(",");
return ("#" + parseInt(new_rgb_list[0]).toString(16) + parseInt(new_rgb_list[1]).toString(16) + parseInt(new_rgb_list[2]).toString(16));
}
colord 包可能是最好的选择,它小巧而强大。
import { colord } from "colord";
colord("rgb(192, 192, 192)").toHex();