2013-05-17 108 views
0

我發現這個代碼在網上,但它不會做我想做的。十六進制轉換到一個打火機十六進制顏色

function ColorLuminance(hex, lum) { 
    // validate hex string 
    hex = String(hex).replace(/[^0-9a-f]/gi, ''); 
    if (hex.length < 6) { 
     hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]; 
    } 
    lum = lum || 0; 
    // convert to decimal and change luminosity 
    var rgb = "#", c, i; 
    for (i = 0; i < 3; i++) { 
     c = parseInt(hex.substr(i*2,2), 16); 
     c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); 
     rgb += ("00"+c).substr(c.length); 
    } 
    return rgb; 
} 

所以我繼續使用jQuery來改變周圍框的背景顏色(被顯示在投票結果(右側),背景色)。

$(".bar-container").each(function() { 
    var hexColor = $(this).children(":first").css("background-color"); 
    var bgColor = ColorLuminance(hexColor, .2); 
    $(this).css({"background-color": bgColor}); 
}); 

這是在文檔準備就緒時使用的。

我所試圖做的是抓住實際調查的顏色(從是個左),使整個容器的顏色有點輕(但相同的基本色)。因此,如果百分比欄是紅色的,則不應將包含欄的整體背景設爲紫色。它應該使它變成紅色的淺色。

ColorLuminance功能無法正常工作,導致它完全改變了顏色!

如何修改這個功能對於較淺的顏色? (最好基於百分比,這就是lum參數)

回答

0

要更改RGB顏色的亮度,我會將其轉換爲HSV顏色空間,您將獲得色調(顏色),飽和度和值(亮度) 。所以你只能改變亮度。

然後你帶回從HSV色彩空間的顏色RGB色彩試。

你可以找到一個HSV逆變器的JavaScript這裏:http://www.javascripter.net/faq/rgb2hsv.htm 有關HSV的更多信息可以在這裏找到:https://en.wikipedia.org/wiki/HSL_and_HSV

Can I force jQuery.css("backgroundColor") returns on hexadecimal format?也可以看看,顏色總是返回已爲RGB看起來。

+1

好了,哇,沒有意識到這是重新調整搶奪元素'backgroundColor'的jQuery的方法的RGB值。問題現在已經解決了。謝謝 :) –