如何无需jQuery选择具有特定背景色的元素?
原生JavaScript实现:筛选div容器中背景色为特定值的span元素
没问题,咱用原生JS就能轻松搞定这个需求,我给你拆解具体步骤和避坑要点:
核心思路
要实现这个需求,关键是获取元素实际渲染的背景色(因为CSS可能是继承、类选择器设置的,不是inline style),然后和目标颜色做匹配,步骤如下:
- 定位目标div容器,获取其中所有span元素
- 遍历每个span,获取它的计算后样式(即浏览器实际渲染的样式)
- 统一颜色格式后,和目标颜色做比较,收集符合条件的元素
示例代码(基础版)
假设你的div有id="target-div",要匹配的背景色是红色(rgb(255, 0, 0),对应十六进制#ff0000):
// 1. 获取目标div容器 const targetDiv = document.getElementById('target-div'); // 2. 获取div下所有span元素 const allSpans = targetDiv.querySelectorAll('span'); // 3. 定义要匹配的目标背景色(推荐用rgb格式,因为getComputedStyle默认返回这个) const targetBg = 'rgb(255, 0, 0)'; // 存储匹配到的元素 const matchedSpans = []; // 遍历所有span,逐一检查 allSpans.forEach(span => { // 获取元素的计算后样式 const computedStyle = window.getComputedStyle(span); // 拿到实际渲染的背景色 const currentBg = computedStyle.backgroundColor; // 比较颜色,注意格式要完全一致 if (currentBg === targetBg) { matchedSpans.push(span); } }); // 现在matchedSpans就是你要的所有符合条件的span console.log('匹配到的span元素:', matchedSpans);
避坑:颜色格式不统一的问题
浏览器返回的backgroundColor格式可能和你写的不一样:比如你写#ff0000,浏览器可能返回rgb(255, 0, 0);如果有透明度,会返回rgba(255, 0, 0, 1)。这时候直接比较字符串会失败,需要统一格式。
解决方法1:统一转成十六进制
写个小工具函数把rgb/rgba转成十六进制,这样就能和你习惯的十六进制颜色比较:
// 把rgb/rgba字符串转成十六进制格式 function rgbToHex(colorStr) { // 匹配rgb(r, g, b)或rgba(r, g, b, a)格式 const match = colorStr.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)/); if (!match) return colorStr; // 不是rgb/rgba格式,直接返回原字符串 const r = parseInt(match[1], 10); const g = parseInt(match[2], 10); const b = parseInt(match[3], 10); // 转成十六进制,自动补零 return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`; } // 使用示例 const targetBgHex = '#ff0000'; allSpans.forEach(span => { const currentBg = window.getComputedStyle(span).backgroundColor; const currentBgHex = rgbToHex(currentBg).toLowerCase(); // 统一小写,避免#FF0000和#ff0000不匹配 if (currentBgHex === targetBgHex.toLowerCase()) { matchedSpans.push(span); } });
解决方法2:只比较RGB数值(忽略透明度)
如果不需要考虑透明度,直接提取RGB数值比较更稳妥:
// 从颜色字符串中提取RGB数值数组 function extractRgb(colorStr) { const match = colorStr.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)/); return match ? [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])] : null; } // 目标RGB数值 const targetRgb = [255, 0, 0]; allSpans.forEach(span => { const currentBg = window.getComputedStyle(span).backgroundColor; const currentRgb = extractRgb(currentBg); // 比较RGB数值 if (currentRgb && currentRgb.every((val, index) => val === targetRgb[index])) { matchedSpans.push(span); } });
注意事项
window.getComputedStyle()返回的是元素实际渲染的样式,不管样式是来自inline、内部CSS还是外部样式表,都能正确获取- 如果div容器是动态生成的,要确保在DOM加载完成后再执行代码(比如放在
DOMContentLoaded事件里)
内容的提问来源于stack exchange,提问作者MongoLato




