我不能用 if else 语句改变我的背景颜色
i cant change my background color with if else statements
我正在尝试制作一个将背景颜色更改为输入颜色的功能。该功能似乎有效,但仅变为黄色。这让我相信 if else 语句有问题,但我无法弄清楚。
var colore = document.getElementById("colors");
function changecolor() {
if (colore = "yellow"){
document.body.style.backgroundColor = "yellow";
}else if (colore = "blue"){
document.body.style.backgroundColor = "blue";
}else if (colore = "green"){
document.body.style.backgroundColor = "green";
}else if (colore = "black"){
document.body.style.backgroundColor = "black";
}else {document.getElementById("error").innerHTML =
"Enter a Valid Color";}
}
您的代码有一些错误,我已修复,详情如下
- 要获得
input
值,您需要像 document.getElementById("colors").value
一样访问 .value
- 你需要一直获取函数内部文本框的值
- 你的条件需要用
===
来比较。 Single =
是一个赋值运算符,您的代码每次都只是分配黄色。另请阅读 Which equals operator (== vs ===) should be used in JavaScript comparisons?
下面的工作代码
function changecolor() {
var colore = document.getElementById("colors").value;
document.getElementById("error").innerHTML=""; // remove existing error
if (colore === "yellow") {
document.body.style.backgroundColor = "yellow";
} else if (colore === "blue") {
document.body.style.backgroundColor = "blue";
} else if (colore === "green") {
document.body.style.backgroundColor = "green";
} else if (colore === "black") {
document.body.style.backgroundColor = "black";
} else {
document.getElementById("error").innerHTML =
"Enter a Valid Color";
}
}
<input id="colors" type="text" />
<button onClick="changecolor()">Change</button>
<p id="error"></p>
我正在尝试制作一个将背景颜色更改为输入颜色的功能。该功能似乎有效,但仅变为黄色。这让我相信 if else 语句有问题,但我无法弄清楚。
var colore = document.getElementById("colors");
function changecolor() {
if (colore = "yellow"){
document.body.style.backgroundColor = "yellow";
}else if (colore = "blue"){
document.body.style.backgroundColor = "blue";
}else if (colore = "green"){
document.body.style.backgroundColor = "green";
}else if (colore = "black"){
document.body.style.backgroundColor = "black";
}else {document.getElementById("error").innerHTML =
"Enter a Valid Color";}
}
您的代码有一些错误,我已修复,详情如下
- 要获得
input
值,您需要像document.getElementById("colors").value
一样访问 - 你需要一直获取函数内部文本框的值
- 你的条件需要用
===
来比较。 Single=
是一个赋值运算符,您的代码每次都只是分配黄色。另请阅读 Which equals operator (== vs ===) should be used in JavaScript comparisons?
.value
下面的工作代码
function changecolor() {
var colore = document.getElementById("colors").value;
document.getElementById("error").innerHTML=""; // remove existing error
if (colore === "yellow") {
document.body.style.backgroundColor = "yellow";
} else if (colore === "blue") {
document.body.style.backgroundColor = "blue";
} else if (colore === "green") {
document.body.style.backgroundColor = "green";
} else if (colore === "black") {
document.body.style.backgroundColor = "black";
} else {
document.getElementById("error").innerHTML =
"Enter a Valid Color";
}
}
<input id="colors" type="text" />
<button onClick="changecolor()">Change</button>
<p id="error"></p>