点击元素实现米色与红色背景互切功能运行异常求助
问题原因
你代码里的逻辑错误主要有两个:
- 判断条件误用赋值运算符
=:if (exp.style.backgroundColor = "beige")这里是直接给背景色赋值为米色,不是判断相等,该表达式永远返回真值,所以每次点击都会直接把背景改成红色,不会进入else分支 - 赋值操作误用比较运算符
==:else if分支里exp.style.backgroundColor == "beige"是判断相等的逻辑,没有完成赋值操作,就算走到这个分支也不会把背景改回米色
修正后的JS代码
let exp = document.querySelector("#lorem") exp.style.backgroundColor = "beige" exp.addEventListener("click", colorChange) function colorChange() { // 判断相等用===,赋值用= if (exp.style.backgroundColor === "beige") { exp.style.backgroundColor = "red" } else if (exp.style.backgroundColor === "red") { exp.style.backgroundColor = "beige" } }
更简洁的实现方案(可选)
你也可以通过切换CSS类的方式实现,后期维护更方便:
首先在CSS中新增红色背景类:
.red-bg { background-color: red; }
JS代码可以简化为:
let exp = document.querySelector("#lorem") exp.style.backgroundColor = "beige" exp.addEventListener("click", () => exp.classList.toggle('red-bg'))
内容的提问来源于stack exchange,提问作者berboş
相关产品推荐
相关产品推荐

