jquery颜色变暗代码返回4位十六进制代码

时间:2016-09-13 14:30:22

标签: jquery

我做了一些代码来动态地使按钮的框阴影成为其背景颜色的较暗版本,但有时它返回一个4位十六进制代码,它不起作用。 你能告诉我代码有什么问题吗?

例如#0fe93b

function rgb2hex(rgb){
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" + ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);}

function LightenDarkenColor(col, amt) {
var usePound = false;
if (col[0] == "#") {
    col = col.slice(1);
    usePound = true;
}
var num = parseInt(col,16);
var r = (num >> 16) + amt;
if (r > 255) r = 255;
else if  (r < 0) r = 0;
var b = ((num >> 8) & 0x00FF) + amt;
if (b > 255) b = 255;
else if  (b < 0) b = 0;
var g = (num & 0x0000FF) + amt;
if (g > 255) g = 255;
else if (g < 0) g = 0;
return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);}

$("input[type=submit]").each(function() {
//get button color
var btnclr = $(this).css("background-color");
//make darker
$(this).css({"box-shadow": "0 -3px 20px " + LightenDarkenColor(rgb2hex(btnclr), -80) + " inset"});
});

1 个答案:

答案 0 :(得分:0)

您的示例仅返回4位数字,因为红色和蓝色都变为0,没有&#39;填充&#39;每种颜色两位数。 (预计:"#009900",实际:"#9900"

你也有一些标记错误的颜色,它应该是红色,绿色,蓝色。

这是更新的LightenDarkenColor函数(带有填充零的额外函数):

function padZero(str, n) {
    str = str.toString()
    while (str.length < n) {
        str = "0" + str;
    }
    return str;
}

function LightenDarkenColor(col, amt) {
    var usePound = false;
    if (col[0] == "#") {
        col = col.slice(1);
        usePound = true;
    }
    var num = parseInt(col,16);

    var r = (num >> 16) + amt;
    if (r > 255) r = 255; else if (r < 0) r = 0;

    var g = ((num >> 8) & 0x00FF) + amt;
    if (g > 255) g = 255; else if (g < 0) g = 0;

    var b = (num & 0x0000FF) + amt;
    if (b > 255) b = 255; else if (b < 0) b = 0;

    return (usePound?"#":"") + padZero(r.toString(16), 2) + padZero(g.toString(16), 2) + padZero(b.toString(16), 2);
}

现在,当您运行LightenDarkenColor("#0fe93b",-80)时,它会返回"#009900"