如何使用CSS或JS动态为多组连续同类元素的首尾项设置样式
实现方案
方案1:JS实现(全浏览器兼容,推荐)
通过遍历列表元素对比相邻节点类名,为连续同组的首尾元素添加自定义标记类,适配所有浏览器场景。
// 按需修改目标类名、父元素选择器即可 const listItems = document.querySelectorAll('.box li'); const targetClasses = ['one', 'two']; // 可配置多个需要匹配的类 targetClasses.forEach(cls => { listItems.forEach((item, index) => { const prevItem = listItems[index - 1]; const nextItem = listItems[index + 1]; // 标记组首:自身包含目标类,前一个节点不存在/不包含目标类 if (item.classList.contains(cls) && (!prevItem || !prevItem.classList.contains(cls))) { item.classList.add(`${cls}-group-first`); } // 标记组尾:自身包含目标类,后一个节点不存在/不包含目标类 if (item.classList.contains(cls) && (!nextItem || !nextItem.classList.contains(cls))) { item.classList.add(`${cls}-group-last`); } }) })
对应的样式定义示例:
/* 连续.one组首尾样式 */ .one-group-first { margin-top: 10px; background: #f0f9ff; } .one-group-last { margin-bottom: 10px; border-bottom: 1px solid #ddd; } /* 连续.two组首尾样式 */ .two-group-first { margin-top: 10px; background: #fff7ed; } .two-group-last { margin-bottom: 10px; border-bottom: 1px solid #ddd; }
方案2:纯CSS实现(需兼容:has()选择器)
如果项目无需兼容Chrome 105以下、Firefox 121以下、Safari 15.4以下版本,可直接用原生CSS实现:
/* 匹配每组.two的首元素 */ .two:first-child, :not(.two) + .two { background: #fff7ed; margin-top: 10px; } /* 匹配每组.two的尾元素 */ .two:last-child, .two:has(+ :not(.two)) { border-bottom: 1px solid #ddd; margin-bottom: 10px; } /* 匹配每组.one的首元素 */ .one:first-child, :not(.one) + .one { background: #f0f9ff; margin-top: 10px; } /* 匹配每组.one的尾元素 */ .one:last-child, .one:has(+ :not(.one)) { border-bottom: 1px solid #ddd; margin-bottom: 10px; }
内容的提问来源于stack exchange,提问作者STeveBobJohn
相关产品推荐
相关产品推荐

