gpt4 book ai didi

javascript - 使用 Javascript 更改文本的颜色

转载 作者:行者123 更新时间:2023-11-30 15:44:00 24 4
gpt4 key购买 nike

我正在尝试制作一个程序,其中我使用一个函数来使用数组和 for 循环更改预先编写的文本的颜色,具体取决于用户在提示时输入的内容。这是我的代码:

// <Student Name> <Student ID> comment must be here.

// This function will change the color of the text to the name of the color you give it.
function changeColor(colorText) {
var text = document.getElementById("colorpar");
text.innerHTML = "<font color=\"" + colorText + "\">The color is " + colorText + ".</font>";
}


// Declare, create, and put values into your color array here
var colors = new Array(5);

colors[0] = "green";
colors[1] = "blue";
colors[2] = "yellow";
colors[3] = "orange";
colors[4] = "red";


// Create a loop that runs 4 times.
// Each time it asks the user for a number between 0 and 4.
// If an invalid input is entered, the color displayed should be black.
// Otherwise display the color at that index in the array.
for (var i = 1; i <= 4; i++) {
var colNumber = window.prompt("Enter a number from 0 to 4:");
if (colNumber == 0 || colNumber == 1 || colNumber == 2 || colNumber == 3 || colNumber == 4) {
changeColor(colors[colNumber]);
} else {
changeColor("black");
}
}
<html>

<head>
<title>Lab 7 Task 2</title>
</head>

<body bgcolor="white">
<h1 id="colorpar">
The color is black.
</h1>

<h1>
</h1>
</body>

</html>

只有在我完成所有提示后,文本才会显示。它显示了正确的颜色和文本以及所有内容,但在开始时显示“颜色为黑色”。不显示,在回答最后一个提示之前什么也不做。

请注意,这是针对初学者的类(class),因此任何比我这里所提供的高级得多的内容都不会有太大帮助。我没有写函数,它作为作业的一部分存在。我已经处理了好几个小时了,但无法弄清楚问题所在!

最佳答案

为此使用 SetInterval。

检查下面的代码片段

function changeColor(colorText) {
var text = document.getElementById("colorpar");
text.innerHTML = "<font color=\"" + colorText + "\">The color is " + colorText + ".</font>";
}


// Declare, create, and put values into your color array here
var colors = new Array(5);

colors[0] = "green";
colors[1] = "blue";
colors[2] = "yellow";
colors[3] = "orange";
colors[4] = "red";


// Create a loop that runs 4 times.
// Each time it asks the user for a number between 0 and 4.
// If an invalid input is entered, the color displayed should be black.
// Otherwise display the color at that index in the array.
var x = 0;
var intervalId = setInterval(function() {
if (x == 4) {
clearInterval(intervalId);
}
var colNumber = window.prompt("Enter a number from 0 to 4:");
if (colNumber == 0 || colNumber == 1 || colNumber == 2 || colNumber == 3 || colNumber == 4) {
setTimeout(changeColor(colors[colNumber]), 1000);

} else {
changeColor("black");
}
x++;
}, 100);
<body bgcolor="white">
<h1 id="colorpar">
The color is black.
</h1>

<h1>
</h1>
</body>

希望对你有帮助

关于javascript - 使用 Javascript 更改文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40372481/

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