0

所以我想让文本中的每个单词都变成不同的颜色,但我只找到了让文本中的每个字母都变成不同颜色的代码。有什么办法可以改变每个单词而不是每个字母的颜色?

<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

4 回答 4

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

在这个 JSFiddle上看到它

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

于 2012-09-29T12:57:22.533 回答
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>');
}
于 2012-09-29T12:58:13.573 回答
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>');
}

小演示:小链接

于 2012-09-29T13:00:17.113 回答
0

让我们尝试一些不同的方式。现场演示。

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);
​
于 2012-09-29T13:03:51.900 回答