1

Not sure if the title explains itself, but probably not!

Anyway, I have 50 divs and I would like to set the background color from White to Dark Yellow. The first div would be white and the last dark yellow.

The RGB value for white is 255, 255, 255 The RGB value for dark Yellow is 227, 151, 4

How could I do that with javascript (jQuery) so iterate through each div and make it gradually get darker?

Here's a screen shot enter image description here Thanks a lot

4

3 回答 3

3
var divs = $('div'),
    len = divs.length;

var targ_R = 227,
    targ_G = 151,
    targ_B = 4,

    inc_R = (255 - targ_R) / len,
    inc_G = (255 - targ_G) / len,
    inc_B = (255 - targ_B) / len;

divs.css("backgroundColor", function(i, curr) {
    return "#" + toHex(255 - (i * inc_R)) +
                 toHex(255 - (i * inc_G)) +
                 toHex(255 - (i * inc_B));
});

function toHex(n) {
    var h = (~~n).toString(16);
    if (h.length < 2)
        h = "0" + h;
    return h;
}

DEMO: http://jsfiddle.net/RSyCM/

于 2012-08-14T16:47:51.083 回答
2

Try this - DEMO

var r, g, b;

for (var i = 0, count = $("div").length; i < count; i++) {
    r = 255 - i * 3;
    g = 255 - i * 10;
    b = 255 - i * 25;

    $("div").eq(i).css("background", "rgb(" + r + ", " + g + ", " + b + ")");
}

UPDATE

To make the last one rgb(227, 151, 4) - DEMO

于 2012-08-14T16:39:09.290 回答
0

Here's a variation of Zoltan Toth's answer using the pusher.color library, in case you want to use a library to handle the parsing and blending.

DEMO

var color0 = pusher.color('white');
var color1 = pusher.color('rgb', 227, 151, 4);

for (var i = 0, count = $("div").length; i < count; i++) {
    var amount = i / (count-1);
    var result = color0.blend(color1, amount);
    $("div").eq(i).css("background", result.html());
}

​</p>

于 2012-08-14T21:30:58.693 回答