You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击元素实现米色与红色背景互切功能运行异常求助

问题原因

你代码里的逻辑错误主要有两个:

  • 判断条件误用赋值运算符=: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ş

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:57:00