在使用ag-grid的时候有通过单元格的值设置不同行颜色,然后百度了网上的方法,汇总了一下,具体效果图如下:
话不多说,直接上代码。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>ag-grid 列组</title>
<script type="text/javascript" src="../js/ag-grid-enterprise.min.js"></script>
</head>
<body>
<div id="myGrid" style="width: 100%;height: 500px;" class="ag-theme-alpine"></div>
<script>
var columnDefs = [
{
headerName: '基本信息',
children: [
{
headerName: '班级',
field: 'class',
cellRenderer: changeCellColor
}, {
headerName: '姓名',
field: 'name',
cellRenderer: changeCellColor
}
]
},
{
headerName: '分数',
children: [
{
headerName: '总分',
field: 'total',
cellRenderer: changeCellColor
},
{
headerName: '语文',
field: 'chinese',
cellRenderer: changeCellColor
},
{
headerName: '数学',
field: 'math',
cellRenderer: changeCellColor
},
{
headerName: '英语',
field: 'english',
cellRenderer: changeCellColor,
}
]
}
];
var data = [
{
class: '一班',
name: '王五',
total: '260',
chinese: '80',
math: '90',
english: '90'
}, {
class: '二班',
name: '张三',
total: '200',
chinese: '70',
math: '100',
english: '30'
}, {
class: '二班',
name: '李四',
total: '270',
chinese: '89',
math: '91',
english: '90'
}, {
class: '三班',
name: '小明',
total: '300',
chinese: '100',
math: '100',
english: '100'
}, {
class: '三班',
name: '小红',
total: '265',
chinese: '88',
math: '90',
english: '87'
}, {
class: '三班',
name: '小华',
total: '290',
chinese: '100',
math: '100',
english: '90'
}
];
var gridOptions = {
defaultColDef: {
sortable: true,
resizable: true,
filter: true,
},
debug: true,
columnDefs: columnDefs,
rowData: data,
// 对表格行的属性进行测试
getRowStyle: ChangRowColor
};
document.addEventListener('DOMContentLoaded', function () {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
});
// 渲染行的颜色
function ChangRowColor(params) {
if (parseInt(params.node.id) % 2 == 0) {
return {
'background-color': 'Violet' //颜色可以用英文、rgb以及十六进制
}
}
else {
return {
'background-color': '#00BFFF'
}
}
}
//渲染单元格属性
function changeCellColor(params) {
//颜色可以用英文、rgb以及十六进制
if (params.data.class === '一班') {
return ('<span style="color:#DC143C;font-weight:bold">' + params.value + '</span>'); //字体颜色为红色
}
else if (params.data.class === '二班') {
return ('<span style="display:table; width:100%; background-color:rgb(119,136,153);">' + params.value + '</span>');//背景颜色为灰色
}
else if (params.value === '小红') {
return ('<span style="Color:yellow">' + params.value + '</span>'); //渲染一个单元格颜色
}
else {
return ('<span style="Color:black">' + params.value + '</span>');
}
}
</script>
</body>
</html>
这个是分别通过这两个网页学习而来:
https://blog.csdn.net/weixin_36706903/article/details/86747993