有没有办法让CSS中的每个单词都有不同的颜色?

时间:2012-09-29 12:49:35

标签: javascript html css

所以我想让文本中的每个单词都有不同的颜色,但我只找到代码,使文本中的每个字母都有不同的颜色。是否有任何方法可以改变每个字中的颜色而不是每个字母?

<script type="text/javascript">
       var message = "The quick brown fox.";
       var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, blue
       for (var i = 0; i < message.length; i++)
          document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>");
    </script>

4 个答案:

答案 0 :(得分:2)

需要进行小的更改。

按空格(" "

将消息拆分为数组
   var message = "The quick brown fox.";
   var messageArr = message.split(" ");
   var colors = ["#ff0000","#00ff00","#0000ff"]; // red, green, blue
   for (var i = 0; i < messageArr .length; i++)
   {
      document.write("<span style='color:" + colors[(i % colors.length)] + ";'>" + messageArr[i] + " </span>");
   }

this JSFiddle

上查看

注意:我还将您的colors数组定义更改为使用数组文字符号[],这是一种更好的声明数组的方法。

答案 1 :(得分:1)

var message = "The quick brown fox.",
    words   = message.split(/\s+/),
    colors  = ['#ff0000', '#00ff00', '#0000ff'];

for (var i = 0; i < words.length; i++) {
    document.write('<span style="color: ' + colors[(i % colors.length)] + ';">' + words[i] + '</span>');
}

答案 2 :(得分:1)

var text = "Glee is very very awesome!";
text = text.split(" ");
var colors = ["red", "green", "rgb(0, 162, 232)"]; //you can use color names, as well as RGB notation
var n = colors.length; //no need to re-grab length each time
for(var i = 0; i < text.length; i ++) {
    document.write('<span style = "color: ' + colors[i % n] + '">' + text[i] + '</span>');
}

小演示:little link

答案 3 :(得分:0)

让我们尝试一些不同的方式。的 The live demo.

var message = "The quick brown fox.",
    colors = ["#ff0000","#00ff00","#0000ff"],
    i = 0, len = colors.length;

message = message.replace(/\b(\w+)\b/g, function (match, word) {
    return '<span style="color: ' + colors[(i++ % len)] + ';">' + word + '</span>';
});
document.write(message);
​