我正在尝试制作一个程序,我使用一个函数来改变使用数组和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>
只有在完成所有提示后,文本才会显示。它显示了正确的颜色和文字以及所有内容,但在开始时“颜色是黑色的”。没有显示,在最后一个提示被回答之前什么都没有。
请注意,这是针对初学者课程的,所以任何比我在这里更高级的东西都没有多大帮助。我没有编写函数,它是作为赋值的一部分。我已经在这几个小时了,无法弄清楚这个问题!
答案 0 :(得分:2)
为此使用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>
希望这有帮助