小编典典

如何获得十六进制颜色值而不是 RGB 值?

all

使用以下 jQuery 将获取元素背景颜色的 RGB 值:

$('#selector').css('backgroundColor');

有没有办法获得十六进制值而不是RGB?


阅读 170

收藏
2022-07-09

共1个答案

小编典典

var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");

//Function to convert rgb color to hex format
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

来源

2022-07-09