You need to enable JavaScript to run this app. JS通过style.background获取CSS设置的背景属性返回空值怎么办
优惠活动
大模型
产品
解决方案
定价
更多

JS通过style.background获取CSS设置的背景属性返回空值怎么办

问题原因
  • HTMLElement.style 只能读取元素行内 style 属性中定义的样式,你代码里的 background 是写在CSS样式表规则中的,不属于行内样式,所以通过style.background获取返回空值。
解决方案

有两种常用的解决方式:

方式1:使用window.getComputedStyle获取计算后样式(推荐)

该API可以拿到元素最终生效的所有样式,不管样式是来自行内、样式表还是继承,示例代码如下:

let img1 = document.getElementById("i1");
const computedStyle = window.getComputedStyle(img1);
// 直接打印完整background复合属性
console.log(computedStyle.background);
// 若只需要背景图片地址,单独取backgroundImage属性兼容性更好
console.log(computedStyle.backgroundImage);

注意:不同浏览器返回的background复合属性的格式可能存在差异,仅需要单一属性值时建议直接取对应的单个属性(如backgroundImage、backgroundColor等)。

方式2:将样式直接写在行内style属性中

如果你的场景允许直接修改HTML,可以把背景样式写到元素的行内style属性里,就能直接通过style属性读取:

<div class="container">
  <div class="img" id="i1" style="background: url('img/IMG_2359.jpg')"></div>
  <div class="img" id="i2"></div>
  <div class="img" id="i3"></div>        
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 04:27:04