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

JavaScript检测元素颜色为白色的代码不生效该如何解决

代码不生效的核心原因
  • 你使用的HTMLElement.style属性仅能读取或修改元素的行内样式(即直接写在HTML标签style属性中的样式),你代码中<p>的白色是通过外部CSS规则设置的,没有写入行内样式,所以document.getElementById("lol").style.color取到的是空值,永远无法匹配"white",判断条件不会触发。
  • 额外注意:即使你用正确方法拿到元素生效的颜色值,不同浏览器返回的颜色格式不统一(可能返回rgb(255, 255, 255)、rgba(255, 255, 255, 1)、十六进制色值等),直接和字符串"white"做全等判断也可能匹配失败。
修正方案

使用window.getComputedStyle()获取元素最终生效的计算样式即可,修改后的代码如下:

function myFunction() {
  const targetEl = document.getElementById("lol");
  // 获取元素实际生效的计算样式
  const realStyle = window.getComputedStyle(targetEl);
  // 兼容不同浏览器的颜色返回格式做判断
  if (realStyle.color === "white" || realStyle.color === "rgb(255, 255, 255)") {
    targetEl.style.color = "black";
  }
}

内容的提问来源于stack exchange,提问作者nirualjs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:18:00