4

我需要一个代码来合并 div 中给定数量的颜色以形成图例。我参考了以下示例代码。

$.each(Array(50), function() {
    $("<div>").appendTo(document.body);
});

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

但它只是一种颜色。我需要在这里使用不止一种颜色。预期输出为 在此处输入图像描述

任何人都请帮我做这个。

4

1 回答 1

0

你可以在这里看到它的作用:http: //jsfiddle.net/THEtheChad/M9MYx/1/

count = 100;

colors = [
  [227, 151, 4 ],
  [ 33, 120, 70]
];

$.each(colors, function(i){
  for(var i = 0; i < count; i++){
    var color = '#';

    $.each(this, function(idx, val){
      color += toHex(inv(inc(val), i));
    });

    $('<div>')
      .css('background', color)
      .appendTo(document.body)
    ;//$div
  }
});

function inc(val){
  return (255 - val) / count;
}

function inv(val, i){
  return 255 - (i * val);
}

function toHex(n) {
  var h = (~~n).toString(16);
  if (h.length < 2) h = "0" + h;
  return h;
}
于 2013-07-03T07:12:18.357 回答