可通过遍历DOM节点并用getComputedStyle检查backgroundImage属性查找所有设背景图元素;需判断值是否含"url("且不为"none";优化时应避免全量遍历*,改用标签或class选择器缩小范围,并注意background简写属性已被自动解析。

可以通过遍历 DOM 节点并检查 backgroundImage 样式属性来查找所有设置了背景图片的元素。
使用 getComputedStyle 检查 computed 样式
这是最可靠的方式,因为它获取的是浏览器实际计算后的样式(包括 CSS 类、继承、内联样式等影响):
- 调用
getComputedStyle(el).backgroundImage获取值,该值通常为url("...")、none或多个 url 的组合(如url(...) url(...)) - 判断是否包含
url(字符串即可,注意大小写不敏感,且需排除none和空值 - 示例代码:
function findAllBgImageElements() {
const allElements = document.querySelectorAll('*');
const result = [];
for (const el of allElements) {
const bg = getComputedStyle(el).backgroundImage;
if (bg && bg !== 'none' && /url\(/i.test(bg)) {
result.push(el);
}
}
return result;
}
优化性能:避免全量遍历 *
在大型页面中遍历所有元素(*)开销较大。可改用更聚焦的选择器缩小范围:
- 只检查常见可能设背景图的标签:
div, section, article, header, footer, aside, main, li, button, a - 或结合 class 名筛选:
document.querySelectorAll('.hero, .banner, .card, [style*="background-image"]') - 对内联样式含
background-image的元素做快速初筛,再用getComputedStyle确认
注意 background 属性的复合写法
background 是简写属性,可能隐藏 background-image。仅检查 backgroundImage 已足够,因为 getComputedStyle 会自动解析出最终生效的 background-image 值(即使它来自 background: url(...) center/cover; 这类简写)。
立即学习“Java免费学习笔记(深入)”;
排除伪元素(如 ::before / ::after)
querySelectorAll('*') 不包含伪元素。如需检测,需单独处理:
- 用
window.getComputedStyle(el, '::before')和::after分别获取 - 但无法直接获取伪元素对应的 DOM 节点,只能拿到其样式信息,因此返回结果是“某个元素的 before 有背景图”,而非独立节点


















