表格单元格中的数据根据值的大小来映射成不同的颜色,效果类似:
请给出具体用法,谢谢!
这里使用开源表格组件VTable来实现这个功能。可以通过在columns
中将style
中的bgColor
设置为函数,按照不同数据,返回不同的颜色值,来实现色阶效果:
const BG_COLOR = (args: TYPES.StylePropertyFunctionArg): string => {
const num = args.value;
if (Number(num) > 80) {
return "#6690FF";
}
if (Number(num) > 50) {
return "#84A9FF";
}
if (Number(num) > 20) {
return "#ADC8FF";
}
return "#D6E4FF";
};
const columns = [
{
style: {
bgColor: BG_COLOR
}
}
];
代码参考 Code Example
const BG_COLOR = (args: TYPES.StylePropertyFunctionArg): string => {
const num = args.value;
if (Number(num) > 80) {
return "#6690FF";
}
if (Number(num) > 50) {
return "#84A9FF";
}
if (Number(num) > 20) {
return "#ADC8FF";
}
return "#D6E4FF";
};
const columns = [
{
field: "id",
title: "ID",
width: 80
},
{
field: "value",
title: "progress",
style: {
bgColor: BG_COLOR
},
width: 250
}
];
const option: TYPES.ListTableConstructorOptions = {
records,
columns
};
new ListTable(document.getElementById("container"), option);
在线效果参考:https://codesandbox.io/s/vtable-color-step-n9ngjq
色阶demo:https://visactor.io/vtable/demo/business/color-level
背景色api:https://visactor.io/vtable/option/ListTable-columns-text#styl...
这个可以使用背景色的 alpha 通道实现,但是前提是需要知道最大值和最小值,然后把数据的值映射到 [0, 1] 这个范围内,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Color</title>
<style>
table {
width: 200px;
}
table,
td {
border: 1px solid #333;
}
table thead {
background-color: #333;
color: #fff;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<td>Value</td>
</tr>
</thead>
<tbody id="rows"></tbody>
</table>
<script>
// 可以事先遍历出最大值和最小值
const MAX_VALUE = 1000;
const MIN_VALUE = 10;
// 最大值对应的颜色
const BASE_COLOR = "#00ff00";
/**
* @param {number} - value 数据的值
* @returns {number}- 对应 ALPHA 通道的值
*/
function getRatio(value) {
return (value - MIN_VALUE) / (MAX_VALUE - MIN_VALUE);
}
/**
* @param {number} - value 数据的值
* @param {string} - 16 位表示的颜色值,无 ALPHA 通道
* @returns {string} - 对应 ALPHA 通道的值的十六进制表示
*/
function getHex(value, color) {
const ratio = getRatio(value);
const alpha = Math.floor(ratio * 255);
// 把 alpha 通道的值加到颜色值的后面
return color + alpha.toString(16).padStart(2, "0");
}
document.addEventListener("DOMContentLoaded", () => {
const rows = document.querySelector("#rows");
for (let i = 0; i < 10; i++) {
const td = document.createElement("td");
// 获取一个 MIN_VALUE 到 MAX_VALUE 之间的随机值
const v =
Math.floor(Math.random() * (MAX_VALUE - MIN_VALUE)) + MIN_VALUE;
const color = getHex(v, BASE_COLOR);
td.style.backgroundColor = color;
td.textContent = v;
const tr = document.createElement("tr");
tr.appendChild(td);
rows.appendChild(tr);
}
});
</script>
</body>
</html>
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.3k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
使用
hsl()
颜色值可以很轻松的使用色阶的变化。上面这个转为 HTML 后就是这样了: