gpt4 book ai didi

javascript - 如何遍历字符串的索引并更改每个字母的颜色?

转载 作者:行者123 更新时间:2023-11-27 23:11:14 25 4
gpt4 key购买 nike

我一直在尝试遍历一个字符串并使用其索引更改每个字符的颜色,但我一直收到错误。有帮助吗?

<!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>

最佳答案

您必须将字符与 DOM 元素区分开来。正如其他人所说,将每个字母包装在 <span> 中.

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;
<p id="text">jesus es le tout puissant</p>

一些注意事项:你想要i < text.length , 不是 i <= text.length .我还使用了 i%colors.length作为colors的索引所以当你用完时你会回到开始。

关于javascript - 如何遍历字符串的索引并更改每个字母的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45890746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com