Datatables 数据表条件格式栏
我开发了一个用于可视化某些统计数据的应用程序 我从API接收以下格式的数据:Datatables 数据表条件格式栏,datatables,javascript,jquery,Datatables,Javascript,Jquery,我开发了一个用于可视化某些统计数据的应用程序 我从API接收以下格式的数据: { "data": [{ "companyName": "company1", "growth": 15 }, { "companyName": "company2", "growth": -8 }, { "companyName": "company3", "growth": 23
{
"data": [{
"companyName": "company1",
"growth": 15
},
{
"companyName": "company2",
"growth": -8
},
{
"companyName": "company3",
"growth": 23
}]
}
这基本上是一个公司名称及其同比收入增长率(%)
我想实现的是一个类似MS Excel的条件格式功能,它在百分比单元格中对条进行着色(条的颜色为红色表示负值,绿色表示正值,其大小标准化为最小/最大值和列宽)
到目前为止,我的HTML是:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js" charset="utf8"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<table id="revenue-growth"></table>
所以,我的问题是:有没有一种方法可以从头开始实现这种特性,或者,可能已经有插件可以做到这一点
在stackoverflow,我在这里找不到任何与我的请求相匹配的东西,也找不到可以解决我问题的DataTables API方法,因此如果您能为我指出正确的方向,我将非常感激。您可以使用
render
-回调在生长列的单元格内创建条形图
$(文档).ready(函数(){
常量数据集=[
{公司名称:“A公司”,成长:-12},
{公司名称:“B公司”,增长:31},
{公司名称:“C公司”,增长:7},
{公司名称:“D公司”,增长:0},
{公司名称:“E公司”,成长:-29},
{公司名称:“F公司”,增长:23},
];
//从数据集中获取grwoth的绝对最大值
const maxGrowthValue=Math.max.apply(Math,dataSet.map(函数(项){return Math.abs(项.growth);});
const table=$(“#示例”).DataTable({
数据:数据集,
栏目:[
{
数据:“公司名称”,
标题:“公司名称”,
},
{
数据:“增长”,
标题:“年收入增长率,%”,
//自定义渲染生长列的单元格
呈现:(数据、类型、行、元)=>{
常量isPositive=(数字(数据)>0);
const barWidth=100/maxGrowthValue*Math.abs(数字(数据))*0.5;
const$growthBarContainer=$(''){
课程:“成长条”,
});
常量$growthBar=$(''{
类:“条形图-”+(isPositive?'positive':'negative'),
});
$growthBar.css({
宽度:barWidth.toFixed(2)+'%',
});
$growthBarContainer.append($growthBar);
$growthNumber=$(''{
类:“增长数”,
});
$growthNumber.text(数据+'%');
$growthBarContainer.append($growthNumber);
返回$growthBarContainer.prop(“outerHTML”);
},
},
],
});
});代码>
.growth条{
显示:内联块;
宽度:120px;
高度:12px;
位置:相对位置;
背景色:#eee;
边框:1px实心#4242;
}
.growth bar>.bar{
宽度:0%;
身高:100%;
位置:绝对位置;
}
.growth bar>.bar.bar-负片{
右:50%;
背景色:红色;
}
.growth bar>.bar.bar-阳性{
左:50%;
背景颜色:绿色;
}
.growth bar>.growth number{
位置:绝对位置;
顶部:1px;
右:2px;
颜色:#fff;
/*阴影增强可读性*/
文本阴影:0px-1px-0px-rgba(0,0,0,5)、0px-1px-0px-rgba(0,0,0,5)、1px-0px-0px-rgba(0,0,0,5)、0px-0px-1px-rgba(0,0,0,25)、0px-0px-2px-rgba(0,0,0,5)、0px-0px-3px-rgba(0,0,0,0,75);
字体大小:10px;
线高:12px;
}
谢谢。这几乎正是我一直在寻找的。有没有办法自定义单元格内容,使百分比数字与条形图重叠?我更新了示例,使数字位于条形图内。
$('#revenue-growth').DataTable({
ajax: {
url: 'https://192.168.0.1/revenue',
method: 'GET',
dataSrc: 'data'
}
dom: 'Bfrtip',
pageLength: 50,
order: [0, 'asc']
columDefs: [{
targets: 0,
data: 'companyName',
title: 'Company Name'
}, {
targets: 1,
data: 'growth',
title: 'YoY revenue growth, %'
}
]
})