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

如何仅用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:25:55