您好我正在尝试解决色彩猜谜游戏任务。一切都很好,除了最后一部分,页面的颜色应该根据猜测的颜色改变。
非常感谢任何提示!
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Guessing Color</title>
</head>
<body onload = "doGame()">
<script>
var colors = ["Azure", "Black", "Chocolate", "Cyan", "Grey", "Green", "Ivory", "Lavender", "Navy", "Olive", "Turquoise", "Yellow"];
var target;
var choice;
var numOfGame = 0;
var finished = false;
function doGame(){
var randNum = Math.floor(Math.random() * colors.length);
target = colors[randNum];
alert(colors[randNum]);
while (!finished) {
choice = prompt("Please, guess the color. \n\n Possible colors are: " + colors + ".\n\n" + "What is the color?");
numOfGame++;
finished = checkGuess();
}
}
function checkGuess() {
if ( colors.indexOf(choice) === -1) {
alert("I don’t recognize that color!");
return false;
} else if (choice > target) {
alert("Your color is alphabetically higher than mine. Please, try again");
return false;
} else if (choice < target) {
alert("Your color is alphabetically lower than mine. Please, try again");
return false;
} else {
alert("You won! Number of games played is " + numOfGame);
return true;
document.body.style.backgroundColor = target;
}
}
</script>
</body>
</html>
答案 0 :(得分:2)
在更改颜色之前从checkGuess()返回。所以,把
document.body.style.backgroundColor = target;
之前的
return true;
检查这个小提琴 - https://jsfiddle.net/anuranpal/x4p7grtu/