Javascript 带有背景色的If语句
嗨,我只是想看看这些if语句哪里出了问题,我看不出它们有什么问题,但它们似乎没有按预期工作,这在单击html按钮时太容易切换颜色。我已经确定,当单击按钮时,控制台会显示“button clicked”(按钮已单击)Javascript 带有背景色的If语句,javascript,html,css,Javascript,Html,Css,嗨,我只是想看看这些if语句哪里出了问题,我看不出它们有什么问题,但它们似乎没有按预期工作,这在单击html按钮时太容易切换颜色。我已经确定,当单击按钮时,控制台会显示“button clicked”(按钮已单击) function colorSwitch() { var thediv = document.getElementsByClassName("light"); console.log("Button Clicked"); if(thediv[0].style.backgr
function colorSwitch()
{
var thediv = document.getElementsByClassName("light");
console.log("Button Clicked");
if(thediv[0].style.backgroundColor == "#ff0000")
{
thediv[0].style.backgroundColor = "#ffff00";
}
if(thediv[0].style.backgroundColor == "#ffff00")
{
thediv[0].style.backgroundColor = "#00ff00";
}
if(thediv[0].style.backgroundColor == "#00ff00")
{
thediv[0].style.backgroundColor = "#ff0000";
}
};
您正在覆盖每个if块的背景色。您需要将其更改为、切换大小写或使用对象来选择新颜色
function colorSwitch()
{
var thediv = document.getElementsByClassName("light");
console.log("Button Clicked");
if(thediv[0].style.backgroundColor == "#ff0000")
{
thediv[0].style.backgroundColor = "#ffff00";
}
else if(thediv[0].style.backgroundColor == "#ffff00")
{
thediv[0].style.backgroundColor = "#00ff00";
}
else if(thediv[0].style.backgroundColor == "#00ff00")
{
thediv[0].style.backgroundColor = "#ff0000";
}
}
或者你可以:
var colorMap = {
"#ff0000": "#ffff00",
"#ffff00":"#00ff00",
"#00ff00": "#ff0000"
}
thediv[0].style.backgroundColor = colorMap[thediv[0].style.backgroundColor];
或:
您需要添加关键字
else
,否则每个条件都会得到满足,从而使您走完整的循环
function colorSwitch () {
var thediv = document.getElementsByClassName("light");
console.log("Button Clicked");
if (thediv[0].style.backgroundColor == "#ff0000") {
thediv[0].style.backgroundColor = "#ffff00";
}
else if (thediv[0].style.backgroundColor == "#ffff00") {
thediv[0].style.backgroundColor = "#00ff00";
}
else if (thediv[0].style.backgroundColor == "#00ff00") {
thediv[0].style.backgroundColor = "#ff0000";
}
};
即使运行此代码:
thediv[0]。style.backgroundColor=“#00ff00”
语句thediv[0].style.backgroundColor==“00ff00”
将返回false(至少对于我的chrome控制台)
另外,正如其他人所指出的,如果每次点击后都有人直接询问语句,则需要使用else一个
;这意味着当你进一步深入研究这个方法时,它们都会变得真实
包括else
语句是一种方法
另一种方法是使用颜色的数组
,假定您需要特定的顺序:
var colors=[“ff0000”、“ffff00”、“00ff00”];
var=0;
函数颜色开关(){
var elements=document.getElementsByClassName(“light”);
元素[0].style.backgroundColor=colors[switched%colors.length];
交换++;
};代码>
.light{
宽度:100px;
高度:3em;
边界半径:.25em;
背景颜色:灰色;
颜色:白色;
线高:3em;
文本对齐:居中;
光标:指针;
}
单击我
似乎需要大量的复制和粘贴。使用对象有更好的方法。仅供参考:并非所有浏览器都返回十六进制。
function colorSwitch () {
var thediv = document.getElementsByClassName("light");
console.log("Button Clicked");
if (thediv[0].style.backgroundColor == "#ff0000") {
thediv[0].style.backgroundColor = "#ffff00";
}
else if (thediv[0].style.backgroundColor == "#ffff00") {
thediv[0].style.backgroundColor = "#00ff00";
}
else if (thediv[0].style.backgroundColor == "#00ff00") {
thediv[0].style.backgroundColor = "#ff0000";
}
};