关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。
想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。
3年前关闭。
Improve this question
var bac=document.querySelector("button");
bac.addEventListener("click", function(){
if (document.body.style.background="white"){
document.body.style.background="purple";
}else if(document.body.style.background="purple"){
document.body.style.background="white";
}
});
为什么此代码将背景颜色更改为紫色 onclick 而不是白色?
最佳答案
您正在使用 =
用于相等比较,但您需要 ==
为了那个原因
var bac=document.querySelector("button");
/* Added the below line because default output of
`document.body.style.background` is "" . Therefore we
need to initialize it first .
*/
document.body.style.background="white";
bac.addEventListener("click", function(){
if (document.body.style.background=="white"){
document.body.style.background="purple";
}else if(document.body.style.background=="purple"){
document.body.style.background="white";
}
});
<button>click</button>
关于Javascript背景颜色切换onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047934/