You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript循环读取ul样式并将背景色与颜色存入单个数组

解决方案:将背景色与文字颜色存入同一数组

当然可以把两类样式存入同一个数组里,咱们只需要把每组的background-color和color打包成对象,再把这些对象依次放进数组即可——这样每组样式是关联在一起的,比分开存两个数组更易维护和使用。

具体实现代码

首先是你的HTML结构(我帮你格式化了一下,方便阅读):

<ul id="list">
  <li>
    <div class="card">
      <div class="test1" style="background-color: #fff333;"></div>
      <p class="test2" style="color: #000;">#ef5777</p>
    </div>
  </li>
  <!-- 可以添加更多li来测试循环效果 -->
  <li>
    <div class="card">
      <div class="test1" style="background-color: #4CAF50;"></div>
      <p class="test2" style="color: #fff;">#4CAF50</p>
    </div>
  </li>
</ul>

然后是JavaScript部分:

// 创建一个数组来存储所有样式组
const stylesArray = [];

// 获取ul下的所有li元素
const listItems = document.querySelectorAll('#list li');

// 循环遍历每个li
listItems.forEach(item => {
  // 找到当前li下的test1和test2元素
  const bgElement = item.querySelector('.test1');
  const colorElement = item.querySelector('.test2');

  // 获取元素的样式(用getComputedStyle可以获取所有样式,包括非内联的)
  const bgColor = window.getComputedStyle(bgElement).backgroundColor;
  const textColor = window.getComputedStyle(colorElement).color;

  // 将当前组的样式打包成对象,存入数组
  stylesArray.push({
    backgroundColor: bgColor,
    textColor: textColor
  });
});

// 测试:打印结果看看
console.log(stylesArray);
// 输出示例:
// [
//   { backgroundColor: 'rgb(255, 243, 51)', textColor: 'rgb(0, 0, 0)' },
//   { backgroundColor: 'rgb(76, 175, 80)', textColor: 'rgb(255, 255, 255)' }
// ]

关键点说明

  • 为什么用对象?这样每组的背景色和文字颜色是绑定在一起的,后续你要使用某一组的样式时,直接从数组里取对象就能拿到对应的两个值,不用再从两个数组里按索引对应,避免索引错位的问题。
  • 为什么用getComputedStyle?如果你的样式不是内联写在style属性里(比如来自CSS类),element.style是拿不到的,而getComputedStyle可以获取元素最终生效的所有样式,兼容性更好。
  • 循环逻辑:通过querySelectorAll获取所有li,再用forEach遍历,确保每组元素都被处理到。

后续可以做什么?

拿到stylesArray之后,你可以根据需求做各种操作:

  • 遍历数组展示所有样式信息,比如在页面上生成预览色块;
  • 将数组转为JSON格式存储到localStorage,实现样式的本地保存;
  • 根据样式值做筛选,比如找出所有背景色为浅色的条目;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:54:39