Get background-color in #000 format and not RGB [duplicate]

我怕爱的太早我们不能终老 提交于 2020-01-12 08:04:22

问题


With this code, I get the RGB color of any TD in my table :

alert($(this).css('background-color'));

the result is :

rgb(0, 255, 0)

Is it possible with jquery to obtain the #000 format or have I to use a function to transform the rgb in #000 format ?

Thanks in advance for your help


回答1:


Try

var color = '';
$('div').click(function() {
   var hexcolor = $(this).css('backgroundColor');
   hexc(hexcolor);
   alert(color);
});

function hexc(colorval) {
    var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    delete(parts[0]);
    for (var i = 1; i <= 3; ++i) {
        parts[i] = parseInt(parts[i]).toString(16);
        if (parts[i].length == 1) parts[i] = '0' + parts[i];
    }
    color = '#' + parts.join('');

    return color;
}



回答2:


Here's a function I wrote earlier, it does the job for me, and has no looping.

function rgbToHex(total) {
    var total = total.toString().split(',');
    var r = total[0].substring(4);
    var g = total[1].substring(1);
    var b = total[2].substring(1,total[2].length-1);
    return ("#"+checkNumber((r*1).toString(16))+checkNumber((g*1).toString(16))+checkNumber((b*1).toString(16))).toUpperCase();
}
function checkNumber(i){
    i = i.toString();
    if (i.length == 1) return '0'+i;
    else return i;
}

JSFIDDLE



来源:https://stackoverflow.com/questions/15716702/get-background-color-in-000-format-and-not-rgb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!