用JavaScript控制颜色随机,每个柱状图颜色不一样,请留下代码

2025-03-31 22:57:40
推荐回答(4个)
回答1:

颜色的css结构很清晰,使用数组保存随机数就好了。

回答2:

简单的一个Demo示例:



$(document).ready(function(){
var a = randomColor();
alert(a);
});
function randomColor(){
return  '#' +
    (function(color){
     return (color +=  '0123456789abcdef'[Math.floor(Math.random()*16)]) && (color.length == 6) ?  color : arguments.callee(color);
   })('');
}

随机生成6个字符然后再串到一起,闭包调用自身与三元运算符!

回答3:





RandomColor eoore.com
















回答4:






白菜编辑部

* {
margin: 0;
padding: 0;
border: 0;
outline: 0;
vertical-align: baseline;
}

body {
text-shadow: 0px 0px 1px rgb(204, 204, 204);
font: 14px/1.5 Consolas, 微软雅黑;
}


var Bar = function (num, width, height, data, colors)
    {
    this.num = num;
    this.width = width;
    this.height = height;
    this.data = data;
    this.colors = colors;
    }
    
    Bar.prototype.createBar = function ()
    {
    with (this)
    {
    var top = height * 3 / 2;
    var temp = [];
    for ( var i = 0; i < num; i++)
    {
    var div = document.createElement ('div');
    var span = document.createElement ("span");
    var txt = document.createTextNode (data[i] + "%");
    span.appendChild (txt);
    span.style.position = div.style.position = 'absolute';
    var randomColor = 'rgb(' + Math.floor ((Math.random () * 255)) + ','
            + Math.floor ((Math.random () * 255)) + ',' + Math.floor ((Math.random () * 255)) + ')';
    while ((',' + temp.join (',') + ',').indexOf (',' + randomColor + ',') != -1)
    {
    randomColor = 'rgb(' + Math.floor ((Math.random () * 255)) + ','
            + Math.floor ((Math.random () * 255)) + ',' + Math.floor ((Math.random () * 255)) + ')';
    temp.push (randomColor);
    }
    !!colors ? span.style.backgroundColor = colors[Math.floor (Math.random () * 3)]
            : span.style.backgroundColor = randomColor;
    div.appendChild (span);
    div.style.backgroundColor = '#D8D5D5';
    div.style.border = '1px solid black';
    div.style.width = width + 'px';
    span.style.width = data[i] * width / 100 + 'px';
    span.style.height = div.style.height = height + 'px';
    div.style.top = top * i + 'px';
    document.body.appendChild (div);
    }
    }
    }
    
    var DATA = [
            10, 30, 40, 60, 50, 80, 90, 20, 66, 88
    ];
    var COLORS = [
            "green", "red", "blue"
    ];
    onload = function ()
    {
    var bar = new Bar (DATA.length, 350, 20, DATA/* , COLORS */);
    bar.createBar ();
    }