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

如何使用JavaScript单行修改HTMLCollection所有元素的样式

单行实现代码

你可以用下面这行代码完全替换原来逐行设置列表项背景色的6行代码,同时完全保留原有逻辑:

Array.from(carruselLi).forEach((el, idx) => el.style.backgroundColor = idx === positionCarrusel ? 'red' : '#1a1d20');

代码说明

  • Array.from(carruselLi):将类数组结构的HTMLCollection转为标准数组,方便直接调用数组遍历方法
  • 遍历过程中通过三元表达式判断当前元素下标是否等于目标下标positionCarrusel,直接赋值对应的背景色,一步完成全量样式重置+指定项高亮的所有逻辑
    如果需要兼容不支持Array.from的旧浏览器环境,可以用以下替代写法:
[].forEach.call(carruselLi, (el, idx) => el.style.backgroundColor = idx === positionCarrusel ? 'red' : '#1a1d20');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 14:36:02