2013-03-30 29 views
6

有了這個代碼,我得到任何TD的RGB顏色在我的表:獲取#000格式的背景顏色,而不是RGB

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

結果是:

RGB(0 ,255,0)

jquery是否有可能獲得#000格式或讓我使用函數來轉換#000格式的rgb?

在此先感謝您的幫助

+0

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

+0

不知道這是否是你所追求的? [獲取十六進制值,而不是使用jQuery RGB值] [1] [1]:http://stackoverflow.com/questions/1740700/get-hex-value-rather-than- rgb-value-using-jquery – ojhawkins

+0

什麼是jQuery [1] [1]? :O – Jashwant

回答

12

嘗試

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

感謝您的代碼,我將嘗試它。 – beegees

+0

@beegees你試過了嗎? –

+1

我試過了,效果很好,謝謝。 – beegees

0

這裏是我以前寫的功能,它的工作對我來說,並沒有循環。

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

相關問題