2013-03-30 3 views
6

Con questo codice, ho il colore RGB di qualsiasi TD in mia tabella:Get background-color in formato # 000 e non RGB

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

il risultato è:

rgb (0 , 255, 0)

E 'possibile con jquery ottenere il formato # 000 o devo usare una funzione per trasformare il formato rgb in # 000?

Grazie in anticipo per il vostro aiuto

+0

http://stackoverflow.com/questions/1740700/get-hex-value-rather-than-rgb-value-using-jquery – Eli

+0

Non sono sicuro se questo è ciò che siete dopo ? [Get valore esadecimale invece di valore RGB utilizzando jQuery] [1] [1]: http://stackoverflow.com/questions/1740700/get-hex-value-rather-than- rgb-value-using-jquery – ojhawkins

+0

cos'è jQuery [1] [1]? : O – Jashwant

risposta

12

Prova

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; 
} 
+0

Grazie per il tuo codice, ho intenzione di provarlo. – beegees

+0

@beegees hai provato? –

+1

Ho provato e funziona benissimo, grazie. – beegees

0

Ecco una funzione che ho scritto in precedenza, lo fa il lavoro per me, e non ha alcun loop.

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