如何仅用CSS根据Span文本内容设置动态数据表文字颜色?
仅用CSS根据文本内容设置库存状态颜色
现代浏览器方案(使用:has()和:contains()伪类)
如果你的项目只需要兼容Chrome 121+、Edge 121+等现代浏览器,可以直接通过CSS伪类匹配文本内容来设置颜色:
/* 先定位到库存列(aria-colindex="4"的单元格)内的span */ .fd-datatable .row [aria-colindex="4"] span { font-weight: 500; /* 可选:添加默认样式 */ } /* 匹配文本为"In Stock"的span,设置绿色 */ .fd-datatable .row [aria-colindex="4"]:has(span:contains("In Stock")) span { color: #2ecc71; } /* 匹配文本为"Out of Stock"的span,设置红色 */ .fd-datatable .row [aria-colindex="4"]:has(span:contains("Out of Stock")) span { color: #e74c3c; }
高兼容性方案(推荐)
如果需要兼容更多浏览器(比如Firefox、旧版Chrome),更稳妥的方式是在动态生成HTML时,给库存状态的span添加自定义data属性(比如data-status),再通过CSS属性选择器控制颜色:
修改后的HTML示例:
<div class="fd-datatable"> <div class="innerScrollContainer"> <div class="row" role="row" tabindex="0" aria-rowindex="1" aria-label="row"> <div aria-colindex="1" role="gridcell"> <!-- ... other columns ... --> <div aria-colindex="4" role="gridcell"> <span data-status="in-stock">In Stock</span> </div> <!-- ... other columns ... --> </div> </div> <!-- 另一行示例 --> <div class="row" role="row" tabindex="0" aria-rowindex="2" aria-label="row"> <div aria-colindex="1" role="gridcell"> <!-- ... other columns ... --> <div aria-colindex="4" role="gridcell"> <span data-status="out-of-stock">Out of Stock</span> </div> <!-- ... other columns ... --> </div> </div> </div> </div>
对应的CSS:
.fd-datatable .row [aria-colindex="4"] span[data-status="in-stock"] { color: #2ecc71; } .fd-datatable .row [aria-colindex="4"] span[data-status="out-of-stock"] { color: #e74c3c; }
注意事项
- 用
:contains()匹配文本时,会区分大小写,确保文本内容和伪类里的字符串完全一致。 - 定位
[aria-colindex="4"]是为了只修改库存列的样式,避免影响表格中其他列的span元素。
内容的提问来源于stack exchange,提问作者bxxb
相关产品推荐
相关产品推荐

