Ich versuche, beide meine letzte Warnmeldung "Herzlichen Glückwunsch ..." und die HTML-Hintergrundfarbe Änderung gleichzeitig geschehen zu bekommen. Die Farbänderung passiert nach Ich klicke auf den "OK" -Button der bereits angezeigten Warnmeldung. Wo gehe ich falsch?Warum werden meine Warnmeldung und Hintergrundfarbe nicht gleichzeitig ausgeführt?
Zugegeben, es gibt eine ähnliche Frage, obwohl ich keine Hinweise von den vorgeschlagenen Lösungen erhalten habe.
let myColors = ["red", "purple", "blue",
"orange", "violet", "green",
"amber", "olive", "navy",
"maroon", "lime", "yellow", "chartreuse",
"crimson", "wheat", "deeppink",
"gold", "beige", "turquoise"
];
let yourColor = (prompt("I am thinking of one of these colors:\n\n" + (myColors.sort()).join(", ") + "\n\nWhat color am I thinking of?")).toLowerCase();
function yourGuessedColor() {
while (myColors.indexOf(yourColor) <= -1) {
alert("Sorry, I don't recognize your color.\n\nPlease try again.");
yourColor = (prompt("I am thinking of one of these colors:\n\n" + (myColors.sort()).join(", ") + "\n\nWhat color am I thinking of?")).toLowerCase();
}
return yourColor;
}
let guessedColor = yourGuessedColor();
let guesses = 1;
function colorGame() {
let myFavColor = myColors[Math.floor(Math.random() * myColors.length)];
while (guessedColor != myFavColor) {
if (guessedColor > myFavColor) {
alert("Sorry, your guess is not correct!\n\nHint: your color is alphabetically higher than mine.\n\nPlease try again.");
guessedColor = (prompt("I am thinking of one of these colors:\n\n" + (myColors.sort()).join(", ") + "\n\nWhat color am I thinking of?")).toLowerCase();
} else {
alert("Sorry, your guess is not correct!\n\nHint: your color is alphabetically lower than mine.\n\nPlease try again.");
guessedColor = (prompt("I am thinking of one of these colors:\n\n" + (myColors.sort()).join(", ") + "\n\nWhat color am I thinking of?")).toLowerCase();
}
guesses++;
document.body.style.backgroundColor = myFavColor;
}
return alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game.\n\nYou can see the color in the background.");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Color Guessing Game</title>
</head>
<body onload="colorGame()">
<script type="text/javascript">
</script>
</body>
</html>
Da JavaScript single-threaded ist, und die 'alert()' pausiert die Ausführung bis nach dem es abgewiesen wird. Wenn Sie stattdessen einen modalen Dialog verwenden (im Dokument anstelle von "alert()"), kann die Farbänderung auftreten, sobald der Dialog angezeigt wird. –
Beachten Sie, dass das OP die Hintergrundfarbe vor der Warnung setzt: 'document.body.style.backgroundColor = myFavColor;' kommt vor 'return alert (" Congratulations! ... 'im Code. –
[tag: web-worker] : Verwenden Sie ['WebWorker'] (https://developer.mozilla.org/en/Using_web_workers), um Multi-Threads zu verwalten –