如何拆分字符串并为每个字符分别制作颜色?

时间:2013-10-11 04:08:56

标签: javascript jquery

我有一个字符串"I like you"来自h2元素:"<h2 id="demo">I like you</h2>" 现在我想拆分它,为两个空格之间的每个单词制作颜色。如何更改标签中每个文本的颜色。 我可以为每种颜色使用array [i]。

array[1], color:red
array[2], color:green
array[3], color:blue

onload时的颜色变化。谢谢大家的建议。

3 个答案:

答案 0 :(得分:3)

尝试

var array = ['red', 'green', 'blue'];

$('#demo').html(function(idx, html){
    return $.map(html.split(/\s/), function(value, idx){
        if(idx < array.length){
            return '<span style="color: ' + array[idx] + '">' + value + '</span>'
        } else {
            return value
        }
    }).join(' ');
})

演示:Fiddle

答案 1 :(得分:2)

一个建议,直到你更好地展示你正在寻找的东西

$(document).ready(function(){
  $.each(array, function(id,value) {
    var color = value.strreplace('color:','');
    $('#'+id).css('color', color);
  });
});

答案 2 :(得分:1)

通过简单的Javascript,

function str_split (string, split_length) {
   if (split_length === null) {
    split_length = 1;
  }
  if (string === null || split_length < 1) {
    return false;
  }
  string += '';
  var chunks = [],
    pos = 0,
    len = string.length;
  while (pos < len) {
    chunks.push(string.slice(pos, pos += split_length));
  }

  return chunks;
}
相关问题