简体   繁体   中英

Change Font Colors of specific Elements in Array - Javascript

all.

I am trying to create an array where I can change the color of the fonts within them.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Array Font Colors</title>
</head>

<body>
<script type="application/javascript">
    var colors= new Array("Black", "White", "Yellow");

    for(var a=0; a<colors.length; a++){
        document.write(colors[a]+ "<br>");
        }

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

The above is what I have that makes the array, and displays it. I am not sure how to change the color of each element however to its given array value. For example, since the second array element value is White, make the font color white. I am new to JavaScript and am a bit confused on how this is done.

Thank you

You can try that in both ways by using document.body.innerHTML or document.write

 <!doctype html> <html> <head> <meta charset="utf-8"> <title>Array Font Colors</title> </head> <body> <script type="application/javascript"> var colors= new Array("Black", "White", "Yellow"); for(var a=0; a<colors.length; a++){ // document.body.innerHTML += "<div style='color:" + colors[a] + "'>" + colors[a] + "</div>"; //or document.write("<div style='color:" + colors[a] + "'>" + colors[a] + "</div>"); } </script> </body> </html>

Apply css to document.write

 <html> <head> <meta charset="utf-8"> <title>Array Font Colors</title> </head> <body> <script type="application/javascript"> var colors= new Array("Black", "White", "Yellow"); for(var a=0; a<colors.length; a++){ document.write("<p style='color:"+colors[a]+"'>"+colors[a]+ "</p>"); } </script> </body> </html>

Instead of using document.write , append a span tag to the body .

Replace that document.write statement by

document.body.innerHTML += "<span style='color:" + colors[a] + "'>" + colors[a] + "</span>";

not the best way but try this
document.write(colors[a].fontcolor("yourcolor")+ "<br>")

can be any css color // #db3f3f , "red" etc..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM