2013-03-30 7 views
6

Z tego kodu, otrzymuję kolor RGB jakiegokolwiek TD w moim stole:Get background-color w formacie # 000 i nie RGB

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

wynik jest:

rgb (0 , 255, 0)

Czy jest możliwe, aby jquery uzyskać format # 000 lub użyć funkcji przekształcenia pliku rgb w formacie # 000?

Dzięki z góry za pomoc

+0

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

+0

Nie jestem pewien, czy to jest to, czego po ? [Get wartość sześciokątną zamiast wartości RGB użyciu jQuery] [1] [1]: http://stackoverflow.com/questions/1740700/get-hex-value-rather-than- rgb-value-using-jquery – ojhawkins

+0

co to jest jQuery [1] [1]? : O – Jashwant

Odpowiedz

12

Spróbuj

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

Dziękuję za Twój kod, spróbuję go. – beegees

+0

@beegees próbowaliście? –

+1

Próbowałem i działa świetnie, dziękuję. – beegees

0

Oto funkcja pisałem wcześniej, to nie praca dla mnie, a nie ma pętli.

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

Powiązane problemy