在Web开发中,使用SVG可以轻松绘制矢量图形并通过动画实现复杂动态UI,时间轴就是典型场景。相比用大量div拼接,SVG在缩放和动画控制上更灵活。

一、SVG时间轴的基本结构
一个简单的时间轴通常由一条横线(轴线)、若干个圆点(时间节点)和文本标签组成。我们可以用SVG的line、circle和text元素来构建。
1.1 静态结构示例
下面代码展示了一个包含三个节点的静态时间轴:
<svg width="600" height="120" viewBox="0 0 600 120"> <line x1="50" y1="60" x2="550" y2="60" stroke="#ccc" stroke-width="4"/> <circle cx="50" cy="60" r="8" fill="#409eff"/> <circle cx="300" cy="60" r="8" fill="#409eff"/> <circle cx="550" cy="60" r="8" fill="#409eff"/> <text x="50" y="90" text-anchor="middle" font-size="14">开始</text> <text x="300" y="90" text-anchor="middle" font-size="14">进行中</text> <text x="550" y="90" text-anchor="middle" font-size="14">结束</text> </svg>
二、让时间轴动起来
我们可以使用JavaScript动态改变进度线的长度,模拟时间推进效果。核心思路是再画一条带颜色的线,用stroke-dasharray和stroke-dashoffset控制显示比例。
2.1 动态进度实现
以下示例用JS在2秒内将进度线从0拉到满:
const svgNS = 'http://www.w3.org/2000/svg';
const progress = document.createElementNS(svgNS, 'line');
progress.setAttribute('x1', 50);
progress.setAttribute('y1', 60);
progress.setAttribute('x2', 550);
progress.setAttribute('y2', 60);
progress.setAttribute('stroke', '#409eff');
progress.setAttribute('stroke-width', 4);
const total = 500;
progress.setAttribute('stroke-dasharray', total);
progress.setAttribute('stroke-dashoffset', total);
document.querySelector('svg').appendChild(progress);
let start = null;
function step(ts) {
if (!start) start = ts;
const p = Math.min((ts - start) / 2000, 1);
progress.setAttribute('stroke-dashoffset', total * (1 - p));
if (p < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);三、绑定交互事件
SVG元素支持常规DOM事件。我们可以给每个circle绑定点击,展示对应内容。
3.1 节点点击示例
document.querySelectorAll('circle').forEach((node, i) => {
node.style.cursor = 'pointer';
node.addEventListener('click', () => {
console.log('你点击了第' + (i + 1) + '个时间节点');
});
});四、小结
通过组合SVG基础图形与脚本控制,开发者能以较少代码实现时间轴等复杂动态UI。若需更细腻的缓动,可引入requestAnimationFrame自定义函数或使用动画库辅助。