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

如何在ASP.NET Repeater绑定中动态修改RadButton的:after伪元素背景色

解决方案

CSS 伪元素不属于 DOM 节点,无法直接通过服务端控件属性或 JS 直接修改其样式,你已经在 CSS 中使用了自定义属性 --myColor,直接给按钮宿主元素设置该自定义属性的值即可实现需求,原有 CSS 代码无需任何修改。

修改后的后台代码如下:

protected void Repeater_Buttons_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var currentItem = (e.Item.DataItem as MyItem);
        var radButton = (e.Item.FindControl("MyButton") as RadButton);
        // 直接给按钮元素设置CSS自定义属性,伪元素会自动继承该值
        radButton.Style.Add("--myColor", ColorTranslator.ToHtml(currentItem.BackColor));
    }
}

补充说明

  • 这里用 ColorTranslator.ToHtml 是为了将 .NET 的 Color 类型转换为 CSS 可识别的十六进制颜色格式,如果你 currentItem.BackColor 本身已经是合法的 CSS 颜色字符串,可以去掉转换逻辑直接赋值。
  • ::after 伪元素会自动读取所属按钮元素上设置的 --myColor 值作为背景色,每个 Repeater 项的按钮都可以独立设置不同颜色,不需要预定义多套 CSS 类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:54:00