随机颜色字符串

时间:2014-04-05 19:49:18

标签: javascript

首先,这不是重复:Generate random string/characters in JavaScript

我特别希望字符串从绿色开始变为随机颜色。我在JS写作

function changeColor()
{
  var change;
  for( var i=0; i < 11; i++ )
  {
    change += script.charAt(Math.floor(Math.random() //Input ur suggestion here, I suspect it is the script variable and different colours
    script = document.getElementById('txt');
    script.style.color = "#33cc33";
  }
}

2 个答案:

答案 0 :(得分:1)

使用有效的十六进制颜色值创建一个数组:

var values = ['a', 'b', 'c', 'd', 'e', 'f', '0', '1', ... '9'];

从该数组中获取随机值:

var hex = values[Math.floor(Math.random() * values.length)];

...六次:

var hex = '#';
for (var i = 0; i < 6; i++ ) {
  hex += values[Math.floor(Math.random() * values.length)];
}

这可以成为一个功能:

function getRandomColor() {
    var values = ['a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    var hex = '#';
    for (var i = 0; i < 6; i++) {
        hex += values[Math.floor(Math.random() * values.length)];
    }
    return hex;

}

Fiddle

答案 1 :(得分:1)

for循环立即完成,你需要一个超时来实际看到颜色变化,一个随机颜色生成器来生成颜色,然后扔一个递归的IIFE你就在那里:

var color = '#33cc33',
    elem  = document.getElementById('txt');

(function fn() {
    elem.style.color = color;
    setTimeout(function() {
        color = '#'+Math.floor(Math.random()*16777215).toString(16);
        fn();
    }, 500);
})();

FIDDLE