如何运行字符串索引并更改每个字母的颜色?

时间:2017-08-26 00:04:36

标签: javascript html

我一直试图通过字符串运行并使用其索引更改每个字符的颜色,但我一直收到错误。有什么帮助吗?

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<p id="text">jesus est le tout puissant</p>


<script>
    var text = document.getElementById("text").textContent;
    console.log(text);
    var colors = ["#EF5350","#8BC34A","#69F0AE","#FFC107","#FFD600","#4E342E","#F44336","#E91E63","#9C27B0","#F50057"];
    for(var i =0; i <= text.length; i++) {
     text[i].style.color = colors[i];
    }





</script>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

您必须将字符视为与DOM元素不同。正如其他人所说,用<span>包装每个字母。

&#13;
&#13;
var element = document.getElementById('text');
var text = element.textContent;
console.log(text);
var colors = ["#EF5350","#8BC34A","#69F0AE","#FFC107","#FFD600","#4E342E","#F44336","#E91E63","#9C27B0","#F50057"];
var styledText = '';
for(var i =0; i < text.length; i++) {
    styledText += '<span style="color:' + colors[i%colors.length] + '">' + text[i] + '</span>';
}
element.innerHTML = styledText;
&#13;
<p id="text">jesus es le tout puissant</p>
&#13;
&#13;
&#13;

一些注意事项:您需要i < text.length,而不是i <= text.length。我还使用i%colors.length作为colors的索引,以便在用完时循环回到开头。

答案 1 :(得分:0)

您必须将每个字母包裹在<span>内,以便为每个字母应用自定义CSS。否则它只是纯文本内容,仅此而已。

将每个字母包裹在自己的<span>中,然后遍历<span>标记内的每个#text,并以与示例相同的方式应用CSS。

const colors = ["#EF5350","#8BC34A","#69F0AE","#FFC107","#FFD600","#4E342E","#F44336","#E91E63","#9C27B0","#F50057"];
const text = document.getElementById(”text”);
const letters = text.textContent;

const _fragment = document.createDocumentFragment();

for (let i = 0; i < letters.length; i++) {
    const letter = document.createElement(”span”);
        letter.textContent = letters[i];
        letter.style.color = colors[i % colors.length]; // This makes sure to keep repeating through the colors, no matter the length of the text

    _fragment.appendChild(letter);
}

text.innerHTML = ””; // There are faster and more efficient ways to do this particular step
text.appendChild(_fragment);

答案 2 :(得分:0)

使用jQuery,您可以将每个单个字符插入SPAN,然后通过FOR循环为单个字符着色

&#13;
&#13;
var colors = ["#EF5350","#8BC34A","#69F0AE","#FFC107","#FFD600","#4E342E","#F44336","#E91E63","#9C27B0","#F50057"];

var e = $('#text');
var temp = $('<span/>'); // I create a temporary font for saving characters

for (var i = 0; i < e.text().length; i++) temp.append($('<span/>').text(e.text().charAt(i)).css('color',colors[ i % colors.length])); // I separate each single letter and apply the colors

e.html(temp.html()); // Apply the changes made
&#13;
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<p id="text">jesus es le tout puissant</p>
</body>
</html>
&#13;
&#13;
&#13;