请原谅 super 初学者的麻烦,但是我正在尝试使用javascript开关使div更改颜色。我敢肯定,这个问题与对参数如何工作的基本误解有关,但正如我所说,我是新手。我没有任何错误,它什么也没做。另外,请先在这里发布信息,如果我在帖子中做了任何不当的行为,我深表歉意。

function colorChanger(color) {
  switch(color) {
		case "red":
			document.getElementById("color_box").style.backgroundColor = "red";
			break;
		case "orange":
			document.getElementById("color_box").style.backgroundColor = "orange";
			break;
		case "yellow":
			document.getElementById("color_box").style.backgroundColor = "yellow";
			break;
		case "green":
			document.getElementById("color_box").style.backgroundColor = "green";
			break;
		case "blue":
			document.getElementById("color_box").style.backgroundColor = "blue";
			break;
		case "indigo":
			document.getElementById("color_box").style.backgroundColor = "indigo";
			break;
		case "violet":
			document.getElementById("color_box").style.backgroundColor = "violet";
			break;
	}
}
@viewport {
    zoom: 1.0;
    width: device-width;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

#color_box {
	width: 20rem;
	height: 20rem;
	border: solid 1px;
}
<!DOCTYPE html>
<html>
<head>
	<title>Color Buttons</title>
	<link rel="stylesheet" type="text/css" href="./color_buttons.css">
	<script src="color_buttons.js"></script>
</head>
<body>
<div id="color_box">
</div>
<div id="button_box">
	<button type="button" id="red" onclick="colorChanger(red)">Red</button>
	<button type="button" id="orange" onclick="colorChanger(orange)">Orange</button>
	<button type="button" id="yellow" onclick="colorChanger(yellow)">Yellow</button>
	<button type="button" id="green" onclick="colorChanger(green)">Green</button>
	<button type="button" id="blue" onclick="colorChanger(blue)">Blue</button>
	<button type="button" id="indigo" onclick="colorChanger(indigo)">Indigo</button>
	<button type="button" id="violet" onclick="colorChanger(violet)">Violet</button>
</div>
</body>
</html>

最佳答案

您需要在引号周围加上引号使它们成为字符串。

<button type="button" id="red" onclick="colorChanger('red')">Red</button>

没有引号,它正在寻找一个名为red的变量。

您没有得到错误的原因是因为颜色与按钮的ID相同,并且ID都成为引用相应DOM元素的全局变量。因此,它的行为就像您写的那样:
onclick="colorChanger(document.getElementById('red'))"

由于这不等于switch语句中的任何情况,因此不会发生任何情况。

顺便说一句,为什么还要烦恼switch语句?做就是了:
document.getElementById("color_box").style.backgroundColor = color;

07-24 09:45
查看更多