gpt4 book ai didi

javascript - 在每个循环中为文本添加颜色更改 - JavaScript

转载 作者:行者123 更新时间:2023-11-28 17:45:03 24 4
gpt4 key购买 nike

这实际上是我第一次尝试编码 - 我什至不知道我的问题是否有意义,请耐心等待

无论如何,我已经编写了一个循环并显示数组的代码。

Is it possible to change the colour of the text for each loop?

谢谢大家的帮助:)

<!DOCTYPE html>
<html>
<body>

<h2>Heroes & Their Ratings</h2>
<p><font color="red">This will display some superheroes and their respective ratings:</font></p>
<p id="demo"> </p>


<script> //Starts loop script

var heroes = ["Batman 3", "Superman 4", "Wonderwoman 7", "Flash 10", "Spiderman 17", "Green Lantern 18", "Bat Girl 28","Thor 23","Captain 30","Punisher 2", "Blink 1","Amber 5","Spawn 6","Dart 8", "Destiny 9","Iceman 11", "Magma 12","Dr. Fate 13","Grifter 15","Ice 14","Katana 16","KidFlash 19","Nite Owl 20","Red Arrow 21","Raven 22","V 25","Wildcat 24","Zan 25","TNT 26","Terra 27"]; //Array so heroes variable stores multiple names
var text= '';
var i = 0 //Assigns i a value of 0
for (; i < heroes.length; i++) { // loop runs for every superhero
text += heroes[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;

//Ends loop script </script>



</body>
</html>

最佳答案

是的,有很多方法。其中之一是使用您之前使用的字体标签:

var heroes = ["Batman 3", "Superman 4"];
var colors = ["blue", "green"];
var text= '';
for (var i = 0; i < heroes.length; i++) { // loop runs for every superhero
text += "<font color='"+colors[i]+"'>"+heroes[i] + "</font><br>";
}
document.getElementById("demo").innerHTML = text;
<!DOCTYPE html>
<html>
<body>

<h2>Heroes & Their Ratings</h2>
<p><font color="red">This will display some superheroes and their respective ratings:</font></p>
<p id="demo"> </p>

</body>
</html>

但是 HTML5 不支持字体标签。所以更好的方法是:

text += "<span style='color:"+colors[i]+"'>"+heroes[i] + "</span><br>";

关于javascript - 在每个循环中为文本添加颜色更改 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941245/

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