name: interactive-dashboard-builder description: 使用Chart.js、下拉过滤器和专业样式构建自包含的交互式HTML仪表盘。适用于创建仪表盘、构建交互式报告或生成无需服务器的可共享HTML文件,包含图表和过滤器。
交互式仪表盘构建器技能
构建自包含HTML/JS仪表盘的模式和技术,使用Chart.js、过滤器、交互性和专业样式。
HTML/JS仪表盘模式
基础模板
每个仪表盘遵循此结构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard Title</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.5.1" integrity="sha384-jb8JQMbMoBUzgWatfe6COACi2ljcDdZQ2OxczGA3bGNeWe+6DChMTBJemed7ZnvJ" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0" integrity="sha384-cVMg8E3QFwTvGCDuK+ET4PD341jF3W8nO1auiXfuZNQkzbUUiBGLsIQUE+b1mxws" crossorigin="anonymous"></script>
<style>
/* 仪表盘样式 */
</style>
</head>
<body>
<div class="dashboard-container">
<header class="dashboard-header">
<h1>Dashboard Title</h1>
<div class="filters">
<!-- 过滤器控制 -->
</div>
</header>
<section class="kpi-row">
<!-- KPI卡片 -->
</section>
<section class="chart-row">
<!-- 图表容器 -->
</section>
<section class="table-section">
<!-- 数据表 -->
</section>
<footer class="dashboard-footer">
<span>数据截至:<span id="data-date"></span></span>
</footer>
</div>
<script>
// 嵌入式数据
const DATA = [];
// 仪表盘逻辑
class Dashboard {
constructor(data) {
this.rawData = data;
this.filteredData = data;
this.charts = {};
this.init();
}
init() {
this.setupFilters();
this.renderKPIs();
this.renderCharts();
this.renderTable();
}
applyFilters() {
// 过滤逻辑
this.filteredData = this.rawData.filter(row => {
// 应用每个活动过滤器
return true; // 占位符
});
this.renderKPIs();
this.updateCharts();
this.renderTable();
}
// ... 每个部分的方法
}
const dashboard = new Dashboard(DATA);
</script>
</body>
</html>
KPI卡片模式
<div class="kpi-card">
<div class="kpi-label">总收入</div>
<div class="kpi-value" id="kpi-revenue">$0</div>
<div class="kpi-change positive" id="kpi-revenue-change">+0%</div>
</div>
function renderKPI(elementId, value, previousValue, format = 'number') {
const el = document.getElementById(elementId);
const changeEl = document.getElementById(elementId + '-change');
// 格式化值
el.textContent = formatValue(value, format);
// 计算和显示变化
if (previousValue && previousValue !== 0) {
const pctChange = ((value - previousValue) / previousValue) * 100;
const sign = pctChange >= 0 ? '+' : '';
changeEl.textContent = `${sign}${pctChange.toFixed(1)}% 对比前期`;
changeEl.className = `kpi-change ${pctChange >= 0 ? 'positive' : 'negative'}`;
}
}
function formatValue(value, format) {
switch (format) {
case 'currency':
if (value >= 1e6) return `$${(value / 1e6).toFixed(1)}M`;
if (value >= 1e3) return `$${(value / 1e3).toFixed(1)}K`;
return `$${value.toFixed(0)}`;
case 'percent':
return `${value.toFixed(1)}%`;
case 'number':
if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
if (value >= 1e3) return `${(value / 1e3).toFixed(1)}K`;
return value.toLocaleString();
default:
return value.toString();
}
}
图表容器模式
<div class="chart-container">
<h3 class="chart-title">月度收入趋势</h3>
<canvas id="revenue-chart"></canvas>
</div>
Chart.js集成
折线图
function createLineChart(canvasId, labels, datasets) {
const ctx = document.getElementById(canvasId).getContext('2d');
return new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: datasets.map((ds, i) => ({
label: ds.label,
data: ds.data,
borderColor: COLORS[i % COLORS.length],
backgroundColor: COLORS[i % COLORS.length] + '20',
borderWidth: 2,
fill: ds.fill || false,
tension: 0.3,
pointRadius: 3,
pointHoverRadius: 6,
}))
},
options: {
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'index',
intersect: false,
},
plugins: {
legend: {
position: 'top',
labels: { usePointStyle: true, padding: 20 }
},
tooltip: {
callbacks: {
label: function(context) {
return `${context.dataset.label}: ${formatValue(context.parsed.y, 'currency')}`;
}
}
}
},
scales: {
x: {
grid: { display: false }
},
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return formatValue(value, 'currency');
}
}
}
}
}
});
}
条形图
function createBarChart(canvasId, labels, data, options = {}) {
const ctx = document.getElementById(canvasId).getContext('2d');
const isHorizontal = options.horizontal || labels.length > 8;
return new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: options.label || '值',
data: data,
backgroundColor: options.colors || COLORS.map(c => c + 'CC'),
borderColor: options.colors || COLORS,
borderWidth: 1,
borderRadius: 4,
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: isHorizontal ? 'y' : 'x',
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: function(context) {
return formatValue(context.parsed[isHorizontal ? 'x' : 'y'], options.format || 'number');
}
}
}
},
scales: {
x: {
beginAtZero: true,
grid: { display: isHorizontal },
ticks: isHorizontal ? {
callback: function(value) {
return formatValue(value, options.format || 'number');
}
} : {}
},
y: {
beginAtZero: !isHorizontal,
grid: { display: !isHorizontal },
ticks: !isHorizontal ? {
callback: function(value) {
return formatValue(value, options.format || 'number');
}
} : {}
}
}
}
});
}
环形图
function createDoughnutChart(canvasId, labels, data) {
const ctx = document.getElementById(canvasId).getContext('2d');
return new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: data,
backgroundColor: COLORS.map(c => c + 'CC'),
borderColor: '#ffffff',
borderWidth: 2,
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
cutout: '60%',
plugins: {
legend: {
position: 'right',
labels: { usePointStyle: true, padding: 15 }
},
tooltip: {
callbacks: {
label: function(context) {
const total = context.dataset.data.reduce((a, b) => a + b, 0);
const pct = ((context.parsed / total) * 100).toFixed(1);
return `${context.label}: ${formatValue(context.parsed, 'number')} (${pct}%)`;
}
}
}
}
}
});
}
过滤器变化时更新图表
function updateChart(chart, newLabels, newData) {
chart.data.labels = newLabels;
if (Array.isArray(newData[0])) {
// 多个数据集
newData.forEach((data, i) => {
chart.data.datasets[i].data = data;
});
} else {
chart.data.datasets[0].data = newData;
}
chart.update('none'); // 'none' 禁用动画以即时更新
}
过滤器和交互性实现
下拉过滤器
<div class="filter-group">
<label for="filter-region">区域</label>
<select id="filter-region" onchange="dashboard.applyFilters()">
<option value="all">所有区域</option>
</select>
</div>
function populateFilter(selectId, data, field) {
const select = document.getElementById(selectId);
const values = [...new Set(data.map(d => d[field]))].sort();
// 保留“所有”选项,添加唯一值
values.forEach(val => {
const option = document.createElement('option');
option.value = val;
option.textContent = val;
select.appendChild(option);
});
}
function getFilterValue(selectId) {
const val = document.getElementById(selectId).value;
return val === 'all' ? null : val;
}
日期范围过滤器
<div class="filter-group">
<label>日期范围</label>
<input type="date" id="filter-date-start" onchange="dashboard.applyFilters()">
<span>至</span>
<input type="date" id="filter-date-end" onchange="dashboard.applyFilters()">
</div>
function filterByDateRange(data, dateField, startDate, endDate) {
return data.filter(row => {
const rowDate = new Date(row[dateField]);
if (startDate && rowDate < new Date(startDate)) return false;
if (endDate && rowDate > new Date(endDate)) return false;
return true;
});
}
组合过滤逻辑
applyFilters() {
const region = getFilterValue('filter-region');
const category = getFilterValue('filter-category');
const startDate = document.getElementById('filter-date-start').value;
const endDate = document.getElementById('filter-date-end').value;
this.filteredData = this.rawData.filter(row => {
if (region && row.region !== region) return false;
if (category && row.category !== category) return false;
if (startDate && row.date < startDate) return false;
if (endDate && row.date > endDate) return false;
return true;
});
this.renderKPIs();
this.updateCharts();
this.renderTable();
}
可排序表
function renderTable(containerId, data, columns) {
const container = document.getElementById(containerId);
let sortCol = null;
let sortDir = 'desc';
function render(sortedData) {
let html = '<table class="data-table">';
// 表头
html += '<thead><tr>';
columns.forEach(col => {
const arrow = sortCol === col.field
? (sortDir === 'asc' ? ' ▲' : ' ▼')
: '';
html += `<th onclick="sortTable('${col.field}')" style="cursor:pointer">${col.label}${arrow}</th>`;
});
html += '</tr></thead>';
// 表体
html += '<tbody>';
sortedData.forEach(row => {
html += '<tr>';
columns.forEach(col => {
const value = col.format ? formatValue(row[col.field], col.format) : row[col.field];
html += `<td>${value}</td>`;
});
html += '</tr>';
});
html += '</tbody></table>';
container.innerHTML = html;
}
window.sortTable = function(field) {
if (sortCol === field) {
sortDir = sortDir === 'asc' ? 'desc' : 'asc';
} else {
sortCol = field;
sortDir = 'desc';
}
const sorted = [...data].sort((a, b) => {
const aVal = a[field], bVal = b[field];
const cmp = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
return sortDir === 'asc' ? cmp : -cmp;
});
render(sorted);
};
render(data);
}
仪表盘的CSS样式
颜色系统
:root {
/* 背景层 */
--bg-primary: #f8f9fa;
--bg-card: #ffffff;
--bg-header: #1a1a2e;
/* 文本 */
--text-primary: #212529;
--text-secondary: #6c757d;
--text-on-dark: #ffffff;
/* 数据强调色 */
--color-1: #4C72B0;
--color-2: #DD8452;
--color-3: #55A868;
--color-4: #C44E52;
--color-5: #8172B3;
--color-6: #937860;
/* 状态颜色 */
--positive: #28a745;
--negative: #dc3545;
--neutral: #6c757d;
/* 间距 */
--gap: 16px;
--radius: 8px;
}
布局
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
line-height: 1.5;
}
.dashboard-container {
max-width: 1400px;
margin: 0 auto;
padding: var(--gap);
}
.dashboard-header {
background: var(--bg-header);
color: var(--text-on-dark);
padding: 20px 24px;
border-radius: var(--radius);
margin-bottom: var(--gap);
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
.dashboard-header h1 {
font-size: 20px;
font-weight: 600;
}
KPI卡片
.kpi-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: var(--gap);
margin-bottom: var(--gap);
}
.kpi-card {
background: var(--bg-card);
border-radius: var(--radius);
padding: 20px 24px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.kpi-label {
font-size: 13px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 4px;
}
.kpi-value {
font-size: 28px;
font-weight: 700;
color: var(--text-primary);
margin-bottom: 4px;
}
.kpi-change {
font-size: 13px;
font-weight: 500;
}
.kpi-change.positive { color: var(--positive); }
.kpi-change.negative { color: var(--negative); }
图表容器
.chart-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
gap: var(--gap);
margin-bottom: var(--gap);
}
.chart-container {
background: var(--bg-card);
border-radius: var(--radius);
padding: 20px 24px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.chart-container h3 {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 16px;
}
.chart-container canvas {
max-height: 300px;
}
过滤器
.filters {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
}
.filter-group {
display: flex;
align-items: center;
gap: 6px;
}
.filter-group label {
font-size: 12px;
color: rgba(255, 255, 255, 0.7);
}
.filter-group select,
.filter-group input[type="date"] {
padding: 6px 10px;
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 4px;
background: rgba(255, 255, 255, 0.1);
color: var(--text-on-dark);
font-size: 13px;
}
.filter-group select option {
background: var(--bg-header);
color: var(--text-on-dark);
}
数据表
.table-section {
background: var(--bg-card);
border-radius: var(--radius);
padding: 20px 24px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
overflow-x: auto;
}
.data-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.data-table thead th {
text-align: left;
padding: 10px 12px;
border-bottom: 2px solid #dee2e6;
color: var(--text-secondary);
font-weight: 600;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.5px;
white-space: nowrap;
user-select: none;
}
.data-table thead th:hover {
color: var(--text-primary);
background: #f8f9fa;
}
.data-table tbody td {
padding: 10px 12px;
border-bottom: 1px solid #f0f0f0;
}
.data-table tbody tr:hover {
background: #f8f9fa;
}
.data-table tbody tr:last-child td {
border-bottom: none;
}
响应式设计
@media (max-width: 768px) {
.dashboard-header {
flex-direction: column;
align-items: flex-start;
}
.kpi-row {
grid-template-columns: repeat(2, 1fr);
}
.chart-row {
grid-template-columns: 1fr;
}
.filters {
flex-direction: column;
align-items: flex-start;
}
}
@media print {
body { background: white; }
.dashboard-container { max-width: none; }
.filters { display: none; }
.chart-container { break-inside: avoid; }
.kpi-card { border: 1px solid #dee2e6; box-shadow: none; }
}
大数据集性能考虑
数据大小指南
| 数据大小 | 方法 |
|---|---|
| <1,000 行 | 直接在HTML中嵌入。完全交互性。 |
| 1,000 - 10,000 行 | 在HTML中嵌入。图表可能需要预聚合。 |
| 10,000 - 100,000 行 | 服务器端预聚合。仅嵌入聚合数据。 |
| >100,000 行 | 不适合客户端仪表盘。使用BI工具或分页。 |
预聚合模式
不要在浏览器中嵌入原始数据并聚合:
// 不要:嵌入50,000原始行
const RAW_DATA = [/* 50,000 行 */];
// 做:嵌入前预聚合
const CHART_DATA = {
monthly_revenue: [
{ month: '2024-01', revenue: 150000, orders: 1200 },
{ month: '2024-02', revenue: 165000, orders: 1350 },
// ... 12行而不是50,000
],
top_products: [
{ product: 'Widget A', revenue: 45000 },
// ... 10行
],
kpis: {
total_revenue: 1980000,
total_orders: 15600,
avg_order_value: 127,
}
};
图表性能
- 限制折线图每个系列<500个数据点(如果需要则下采样)
- 限制条形图<50个类别
- 对于散点图,上限1,000个点(大数据集使用采样)
- 对于多图表的仪表盘,禁用动画:在Chart.js选项中设置
animation: false - 过滤器触发更新时使用
Chart.update('none')而不是Chart.update()
DOM性能
- 限制数据表到100-200可见行。更多行添加分页。
- 使用
requestAnimationFrame协调图表更新 - 避免在过滤器更改时重建整个DOM – 仅更新更改的元素
// 高效表分页
function renderTablePage(data, page, pageSize = 50) {
const start = page * pageSize;
const end = Math.min(start + pageSize, data.length);
const pageData = data.slice(start, end);
// 仅渲染pageData
// 显示分页控制:“显示第1-50行,共2,340行”
}