点击网格单元格时保持文本原有颜色,仅修改背景为灰色的实现方法
解决方案
要实现红色背景网格行点击选中后背景变灰色、保留文本原有颜色的效果,核心是为选中状态(.p-highlight类)补充样式规则——现有代码仅处理了非选中行的默认和hover状态,未覆盖选中场景。
方法一:扩展混入实现通用选中样式(推荐)
修改hoverable-row混入,新增对.p-highlight选中状态的处理,让所有行类型都能复用该逻辑:
@mixin hoverable-row($bg-color, $highlight-color: $gray-c5, $hover-color: null) { &:not(.p-highlight) { background-color: $bg-color; &:hover { @if ($hover-color) { background-color: $hover-color; } @else { background-color: rgba($bg-color, 0.6); } } } // 新增选中状态样式:背景设为目标灰色,文本继承原有颜色 &.p-highlight { background-color: $highlight-color; color: inherit; } } tr.p-element.p-selectable-row { &.row-bg-default { @include hoverable-row($default-background, $hover-color: $default-highlight); } &.row-bg-red { // 默认使用混入里的$gray-c5作为选中背景色,如需自定义可传第二个参数 @include hoverable-row($red-background); } &.row-bg-green { @include hoverable-row($green-background); color: inherit; } &.row-bg-yellow { @include hoverable-row($yellow-background); color: inherit; } }
方法二:单独为红色行添加选中样式
如果不想修改通用混入,可直接在.row-bg-red下补充选中状态的规则:
@mixin hoverable-row($bg-color, $highlight-color: $gray-c5, $hover-color: null) { &:not(.p-highlight) { background-color: $bg-color; &:hover { @if ($hover-color) { background-color: $hover-color; } @else { background-color: rgba($bg-color, 0.6); } } } } tr.p-element.p-selectable-row { &.row-bg-default { @include hoverable-row($default-background, $hover-color: $default-highlight); } &.row-bg-red { @include hoverable-row($red-background); // 单独指定红色行选中后的样式 &.p-highlight { background-color: $gray-c5; // 替换为你需要的灰色值 color: inherit; // 保留文本原有颜色(红/黄/绿等) } } &.row-bg-green { @include hoverable-row($green-background); color: inherit; } &.row-bg-yellow { @include hoverable-row($yellow-background); color: inherit; } }
关键说明
.p-highlight是组件标记选中行的类(从现有代码的:not(.p-highlight)可确认),通过为该类设置background-color实现选中后的灰色背景。color: inherit确保文本颜色继承自原有设置,不会被选中状态的样式覆盖,保留原本的红、黄、绿等颜色。
内容的提问来源于stack exchange,提问作者Czesław Nowicki
相关产品推荐
相关产品推荐

