可通过getcomputedstyle获取实际背景色,如getcomputedstyle(document.body).backgroundcolor返回rgb/rgba值;设置时用style.backgroundcolor修改内联样式,需注意透明、继承及css优先级问题。

可以通过 JavaScript 操作 document.body.style.backgroundColor 或 document.documentElement.style.backgroundColor 来获取和设置页面背景色,但需注意默认值、CSS 优先级及透明/继承等特殊情况。
获取当前背景色
直接读取 style.backgroundColor 只能拿到内联样式设置的值,无法获取 CSS 文件或浏览器默认值。推荐使用 window.getComputedStyle() 获取最终渲染值:
- 用
getComputedStyle(document.body).backgroundColor获取 body 的实际背景色(返回 RGB 或 rgba 字符串,如"rgb(255, 255, 255)") - 若页面未显式设置背景色,可能返回
"rgba(0, 0, 0, 0)"(透明)或浏览器默认色(如白色),具体取决于 UA 样式表 - 需要转换为十六进制时,可借助小函数解析 RGB 值再格式化
设置背景色
最常用方式是修改 body 或 html 元素的内联样式:
-
document.body.style.backgroundColor = "#ff6b35"—— 设置十六进制色 -
document.body.style.backgroundColor = "rgba(255, 107, 53, 0.8)"—— 支持透明度 - 若想覆盖根元素(
)背景,用document.documentElement.style.backgroundColor - 注意:设置后会覆盖 CSS 中的 background-color,但不会影响 background-image 等其他背景属性
处理透明与继承情况
当背景色为 transparent 或未定义时,视觉上可能显示父元素或默认色,但 JS 读取结果未必直观:
-
getComputedStyle对 transparent 会返回"rgba(0, 0, 0, 0)",不代表“无色”,而是完全透明 - 如果 body 背景色为
inherit,计算后仍可能返回透明值,实际显示由 html 元素决定 - 稳妥做法:同时检查
document.documentElement和document.body的 computedStyle
兼容性与注意事项
现代浏览器均支持上述方法,但要注意:
- 设置前确保 DOM 已加载(放在
DOMContentLoaded事件中或 script 放在 body 底部) - 避免频繁读写 style 属性,可能触发重排;批量操作建议先读再写
- 暗色模式下,用户系统偏好可能影响初始背景色,可通过
matchMedia("(prefers-color-scheme: dark)")感知
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











