Javascript-If语句工作,但else不工作';T
我有一个脚本,在单击特定元素时运行。脚本更改div的背景色。当用户单击div时,背景色必须更改为#4aa3c3,但当用户再次单击div时,背景色必须更改回#fafafa。if语句有效,但由于某种原因,一旦颜色更改为#4aa3c3,它就不会恢复正常。看来我的else语句不起作用了。我做错什么了吗Javascript-If语句工作,但else不工作';T,javascript,html,colors,onclick,Javascript,Html,Colors,Onclick,我有一个脚本,在单击特定元素时运行。脚本更改div的背景色。当用户单击div时,背景色必须更改为#4aa3c3,但当用户再次单击div时,背景色必须更改回#fafafa。if语句有效,但由于某种原因,一旦颜色更改为#4aa3c3,它就不会恢复正常。看来我的else语句不起作用了。我做错什么了吗 function Active() { if (document.getElementById("test").style.backgroundColor !== "#4aa3c3"){
function Active() {
if (document.getElementById("test").style.backgroundColor !== "#4aa3c3"){
document.getElementById("test").style.backgroundColor = "#4aa3c3";
} else {
document.getElementById("test").style.backgroundColor = "#fafafa";
}
}
当您尝试一些基本调试时,例如
console.log(document.getElementById('test').style.backgroundColor);
你看到问题了吗?很有可能,你会得到如下结果:
"rgb(74, 163, 195)"
这就是为什么if
不能按您希望的方式工作。但这不是你最大的问题
真正的问题是您正在使用表示(CSS)来定义行为(JS)。除此之外,您还可以使用行为来定义表示
相反,您应该这样做:
document.getElementById('test').classList.toggle('toggled');
并使用CSS定义如下样式:
#test {background-color: #fafafa}
#test.toggled {background-color: #4aa3c3}
我同意上面的答案-但是要添加另一个维度-如果您确实需要将返回的RBG值更改为十六进制,您可以尝试类似的方法,这将允许代码按照原始问题中的说明工作
<script>
function hex(x) {
return ("0"+x.toString(16)).slice(-2);
}
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
function CheckIfColorIsCorrect()
{
var hex = rgb2hex(document.getElementById("test").style.backgroundColor);
if (hex != "#4aa3c3"){
document.getElementById("topbar").style.backgroundColor = "#4aa3c3";
} else {
document.getElementById("test").style.backgroundColor = "#fafafa";
}
}
</script>
函数十六进制(x){
返回(“0”+x.toString(16)).slice(-2);
}
函数rgb2hex(rgb){
rgb=rgb.match(/^rgb\(\d+)\s*(\d+)\s*(\d+)$/);
返回“#”+hex(rgb[1])+hex(rgb[2])+hex(rgb[3]);
}
函数CheckIfColorIsCorrect()
{
var hex=rgb2hex(document.getElementById(“test”).style.backgroundColor);
如果(十六进制!=“#4aa3c3”){
document.getElementById(“topbar”).style.backgroundColor=“#4aa3c3”;
}否则{
document.getElementById(“test”).style.backgroundColor=“#fafafa”;
}
}
浏览器报告颜色值的方式可能与您最初使用的颜色代码不一致。添加一个console.log()
调用以查看颜色值的实际值。像MVC大师一样说话谢谢-我应该提到我是Javascript的完全初学者,但我认为您收集了很多。Ew<代码>函数hex(x){return(“0”+x.toString(16)).slice(-2);}比拥有一个hexit:D数组要好得多