2013-05-28 21 views

回答

7

jQuery是沒有必要在這種情況下!

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

hex是十六進制顏色值,並lum是亮度因子,-1 < = LUM < = 1,負數意味着較暗,正打火機

用法:

var newColor = ColorLuminance("#00ff00", -0.5); // "#334d66" - 50% darker 

見a working JSFiddle

來自here的代碼片段