JavaScript垂直时间轴是一种常见的数据可视化方式,用于展示按时间顺序排列的事件或数据点。以下是关于JavaScript垂直时间轴的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方法。
垂直时间轴通常是一个垂直方向的线性图表,其中时间沿水平轴递增,事件或数据点沿垂直轴分布。每个事件通常用一个标记表示,并附带描述性文本或详细信息。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vertical Timeline</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.timeline {
font-family: Arial, sans-serif;
}
.event {
cursor: pointer;
}
</style>
</head>
<body>
<div id="timeline"></div>
<script>
const data = [
{ date: new Date(2020, 0, 1), title: 'Event 1' },
{ date: new Date(2021, 3, 15), title: 'Event 2' },
{ date: new Date(2022, 6, 30), title: 'Event 3' }
];
const margin = { top: 20, right: 30, bottom: 30, left: 40 },
width = 800 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
const x = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([0, width]);
const y = d3.scaleBand()
.domain(data.map(d => d.title))
.range([height, 0])
.padding(0.1);
const svg = d3.select("#timeline")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
svg.selectAll(".event")
.data(data)
.enter().append("rect")
.attr("class", "event")
.attr("x", d => x(d.date))
.attr("y", d => y(d.title))
.attr("width", 20)
.attr("height", y.bandwidth())
.attr("fill", "steelblue")
.on("mouseover", function(event, d) {
d3.select(this).attr("fill", "orange");
})
.on("mouseout", function(event, d) {
d3.select(this).attr("fill", "steelblue");
});
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
</script>
</body>
</html>
moment.js
进行日期解析和格式化。通过以上信息,你应该能够更好地理解和实现JavaScript垂直时间轴,并解决在实际应用中可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云