如何使用getComputedStyle遍历div并动态展示background-color值
实现方案
核心逻辑
- 通过CSS选择器批量匹配所有需要处理的颜色展示div
- 遍历每个匹配到的元素,读取计算生效后的
background-color属性值 - 动态创建DOM节点插入到变量名下方展示色值
可直接复用的代码
把你原有<script>标签内的myFunction函数替换为以下代码即可运行:
function myFunction() { // 选择所有带bg-前缀类的颜色卡片div,可根据你实际的业务类名调整选择器 const colorCards = document.querySelectorAll('.row .col[class*="bg-"]'); // 可选:RGB转HEX格式工具函数,不需要可以删掉 function rgbToHex(rgb) { const result = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); if (!result) return rgb; // 渐变值不转换直接返回原值 const toHex = n => parseInt(n).toString(16).padStart(2, '0').toUpperCase(); return `#${toHex(result[1])}${toHex(result[2])}${toHex(result[3])}`; } colorCards.forEach(card => { // 获取实际生效的背景色值 const bgColor = window.getComputedStyle(card).getPropertyValue('background-color'); // 创建展示色值的节点 const colorValueEl = document.createElement('span'); // 不需要HEX格式就把rgbToHex(bgColor)改成bgColor colorValueEl.textContent = rgbToHex(bgColor); // 可自定义色值展示样式 colorValueEl.style.display = 'block'; colorValueEl.style.marginTop = '8px'; colorValueEl.style.fontSize = '14px'; colorValueEl.style.opacity = '0.9'; // 插入到变量名标题下方 const titleEl = card.querySelector('h2'); titleEl.after(colorValueEl); }); }
自定义调整说明
- 如果你的颜色展示div有统一的自定义类(比如
color-card),可以把选择器替换为.color-card,匹配精度更高 - 可按需调整span的样式规则,适配你的页面视觉风格
内容的提问来源于stack exchange,提问作者J. Patrick Moran
相关产品推荐
相关产品推荐

