下面直接给你最实用、最常见的根据条件设置行背景颜色(row styling)方法,jQuery EasyUI datagrid 支持超级灵活,复制粘贴就能用,领导最爱的“金额超标红色、状态异常高亮、库存不足橙色预警”全都有!
方法1:最简单最常用 – 使用 rowStyler 函数(推荐现在就用这个,3秒出效果)
根据行数据动态返回样式,超级高效!
<table id="dg" class="easyui-datagrid" title="条件行背景颜色示例" style="width:800px;height:400px"
data-options="
url:'data.json',
fitColumns:true,
pagination:true,
rownumbers:true,
singleSelect:false,
showFooter:true,
rowStyler: function(index, row){
// 根据条件返回CSS样式字符串
if (row.amount > 10000){
return 'background-color:#ffcccc;color:#ff0000;font-weight:bold;'; // 金额超1万 红色
}
if (row.quantity < 10){
return 'background-color:#fff3cd;color:#856404;'; // 库存不足10 橙色预警
}
if (row.status == '禁用'){
return 'background-color:#f8f9fa;color:#6c757d;text-decoration:line-through;'; // 禁用 灰色删除线
}
if (row.vip == true){
return 'background-color:#d4edda;color:#155724;border-left:4px solid #28a745;'; // VIP客户 绿色边
}
return ''; // 默认无样式
}
">
<thead>
<tr>
<th data-options="field:'ck',checkbox:true"></th>
<th data-options="field:'id',width:60">ID</th>
<th data-options="field:'name',width:120">商品名称</th>
<th data-options="field:'quantity',width:80,align:'right'">库存数量</th>
<th data-options="field:'amount',width:120,align:'right'">订单金额</th>
<th data-options="field:'status',width:80">状态</th>
<th data-options="field:'vip',width:60,formatter:function(v){return v?'是':'否';}">VIP</th>
</tr>
</thead>
</table>
效果:
- 订单金额 > 10000:整行红色高亮
- 库存 < 10:橙色背景预警
- 状态“禁用”:灰色 + 删除线
- VIP客户:绿色左边框 + 浅绿背景
实时加载、分页、排序全支持!
方法2:更高级 – 结合 styler 函数动态设置(支持列单独颜色)
如果你想某列单独高亮,用 column 的 styler:
<th data-options="
field:'amount',
width:120,
align:'right',
styler: function(value, row, index){
if (value > 10000){
return 'background-color:#ffebee;color:#c62828;font-weight:bold;';
}
return '';
}">
订单金额
</th>
方法3:加载后手动设置行样式(适合复杂条件或异步判断)
$('#dg').datagrid({
onLoadSuccess: function(data){
var rows = data.rows;
for(var i=0; i<rows.length; i++){
var row = rows[i];
var css = '';
if(row.amount > 50000){
css = 'background-color:#ffebee !important;';
} else if(row.quantity == 0){
css = 'background-color:#f8d7da;color:#721c24;';
}
if(css){
// 手动给行tr添加样式(注意索引从0开始)
$(this).datagrid('getRowDetail',i).prev('tr.datagrid-row').attr('style', css);
// 或者更稳的方式:
$('tr[datagrid-row-index='+i+']').css('background-color', '#ffebee');
}
}
}
});
方法4:选中行也保持条件颜色(避免选中蓝色覆盖)
在 rowStyler 里加 !important 或更高优先级:
rowStyler: function(index, row){
if (row.amount > 10000){
return 'background-color:#ffcccc !important;color:#ff0000 !important;';
}
// ...
}
你现在直接复制方法1的 rowStyler 代码到你的 datagrid,刷新一下就能看到根据条件自动变色的行效果了!
结合之前的复选框 + 分页 + 行内编辑 + 页脚摘要 + 合并单元格,你的报表已经可以直接发给领导说“这是高级BI系统”了。
想要我给你一个完整的HTML示例(带远程数据 + 多条件颜色 + 库存预警 + VIP标识 + 选中保持颜色)?
或者你告诉我你的具体条件(比如“余额负数红色”“到期日期接近黄色”“优先级高加粗”),我2分钟发你精准代码,复制就能跑!
快说说你想根据什么字段/条件变色,我手把手帮你搞定,5分钟内看到超级专业的行颜色效果!