PROJECTS / 实战项目

把知识做成能用的东西

五个由浅入深的原生 JavaScript 项目:待办清单、Canvas 画板、手写柱状图、迷你状态管理库、极简路由。 每个项目都从目标拆到代码,完整代码可以单独保存运行,不依赖任何框架、构建工具与外部资源。

5 个完整项目 原生 JavaScript 可直接保存运行 每项目完整代码 80 行以上
Chapter 01 / PERSISTENCE

待办清单 TodoList

用一个最小可用产品,把数据、渲染、事件与持久化串成一条完整的链路。

01

从数据到视图:可持久化的待办清单

难度 · 入门

项目目标

支持新增、勾选完成、删除、按状态筛选、清除已完成,并且刷新页面后数据仍然存在。 这个项目的重点不是界面,而是把一句话落到实处:数据是唯一真相,视图只是数据的投影。 只要这句话守住了,后面无论加编辑、排序还是拖拽,都不会把代码写乱。

技术点

localStorage JSON.stringify 事件委托 单一数据源 渲染函数 Array.filter / map

涉及的知识在基础篇与 DOM 篇都出现过:数组方法负责“改数据”,DOM API 负责“画界面”, 事件委托负责“接住操作”,localStorage 负责“把数据留下来”。这里做的事情是把它们组装起来。

分步实现

  1. 先定数据结构,再想界面。每条待办只需要三个字段:id、text、done。 整个应用只有一个 todos 数组,任何界面变化都必须先改数组,再调用 render()。 读取时用 try/catch 包住,避免存储里的脏数据让页面直接白屏。

    const STORAGE_KEY = 'todolist-demo';
    let todos = load();
    let filter = 'all'; // 'all' | 'active' | 'done'
    
    function load() {
      try {
        const raw = localStorage.getItem(STORAGE_KEY);
        const list = raw ? JSON.parse(raw) : [];
        return Array.isArray(list) ? list : [];
      } catch (err) {
        return []; // 数据损坏时退回空列表
      }
    }
    
    function save() {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
      } catch (err) {
        // 隐私模式或超出配额:保留内存中的数据即可
      }
    }
  2. 渲染函数只做一件事:把数据翻译成 DOM。每次全量清空再重建,写法朴素但状态最可控。 用户输入一律用 textContent 写入,不要拼 innerHTML, 否则一条 <img onerror=...> 就能变成脚本。

    function render() {
      const list = document.getElementById('todoList');
      const items = visibleTodos();
      list.innerHTML = '';
    
      if (items.length === 0) {
        const empty = document.createElement('li');
        empty.className = 'empty';
        empty.textContent = '还没有待办,先写一条。';
        list.appendChild(empty);
      }
    
      items.forEach(todo => {
        const li = document.createElement('li');
        li.dataset.id = todo.id;
        li.className = todo.done ? 'done' : '';
    
        const box = document.createElement('input');
        box.type = 'checkbox';
        box.checked = todo.done;
        box.dataset.act = 'toggle';
    
        const text = document.createElement('span');
        text.className = 'text';
        text.textContent = todo.text; // 不解析 HTML
    
        const del = document.createElement('button');
        del.type = 'button';
        del.className = 'del';
        del.dataset.act = 'del';
        del.textContent = '删除';
    
        li.append(box, text, del);
        list.appendChild(li);
      });
    }
  3. 用事件委托接住所有交互。列表项会不断增删,逐个绑定监听器既繁琐又容易泄漏。 把 change 与 click 挂在 ul 上, 用 event.target.closest('li[data-id]') 找到被操作的条目,再读 data-act 判断动作。

    const list = document.getElementById('todoList');
    
    list.addEventListener('change', event => {
      const li = event.target.closest('li[data-id]');
      if (!li || event.target.dataset.act !== 'toggle') return;
    
      todos = todos.map(todo => {
        return todo.id === li.dataset.id
          ? { ...todo, done: !todo.done }
          : todo;
      });
      commit();
    });
    
    list.addEventListener('click', event => {
      if (event.target.dataset.act !== 'del') return;
      const li = event.target.closest('li[data-id]');
      if (!li) return;
    
      todos = todos.filter(todo => todo.id !== li.dataset.id);
      commit();
    });
  4. 把“保存 + 渲染”收成一个提交函数。新增、切换、删除、清除都走同一条路径, 避免某处忘记持久化。map 与 filter 都会返回新数组, 这样每次变更都发生在唯一入口 commit(),调试时只需要盯住一个地方。

    function commit() {
      save();
      render();
    }
    
    document.getElementById('addForm').addEventListener('submit', event => {
      event.preventDefault();
      const input = document.getElementById('todoInput');
      const text = input.value.trim();
      if (!text) return; // 空输入不产生数据
    
      const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
      todos = [{ id, text, done: false }, ...todos];
      input.value = '';
      commit();
    });
    
    document.getElementById('filters').addEventListener('click', event => {
      const btn = event.target.closest('button[data-filter]');
      if (!btn) return;
      filter = btn.dataset.filter;
      btn.parentElement.querySelectorAll('button').forEach(item => {
        item.classList.toggle('on', item === btn);
      });
      render(); // 只改筛选,不必重新保存
    });
不要用 innerHTML 渲染用户输入。

待办文本来自用户,属于不可信内容。拼接 innerHTML 会让标签被解析, 轻则布局错乱,重则执行脚本。示例统一用 textContent,需要富文本时也应先转义或使用白名单过滤。

完整可运行代码

把下面的内容保存为 todo.html,双击用浏览器打开即可。数据写入当前源的 localStorage,键名为 todolist-demo。代码包含完整的样式、结构与逻辑, 不依赖任何外部文件。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>待办清单 · TodoList</title>
<style>
  :root {
    --paper: #fffdf8;
    --bg: #f7f4ee;
    --ink: #2c352e;
    --mute: #8b968c;
    --line: #dfe3db;
    --sage: #7ba58a;
    --sage-deep: #4f7a60;
    --rose: #c98f8f;
  }
  * { box-sizing: border-box; }
  body {
    margin: 0;
    padding: 48px 18px;
    background: var(--bg);
    color: var(--ink);
    font: 15px/1.7 "PingFang SC", "Microsoft YaHei", sans-serif;
  }
  .app {
    max-width: 520px;
    margin: 0 auto;
    padding: 28px 26px 22px;
    background: var(--paper);
    border: 1px solid var(--line);
    border-radius: 18px;
  }
  h1 { margin: 0 0 2px; font-size: 23px; }
  .sub { margin: 0 0 22px; font-size: 11px; letter-spacing: 0.18em; color: var(--mute); }
  form { display: flex; gap: 8px; }
  #todoInput {
    flex: 1;
    min-width: 0;
    padding: 10px 13px;
    border: 1px solid var(--line);
    border-radius: 10px;
    font: inherit;
    outline: none;
  }
  #todoInput:focus { border-color: var(--sage); }
  form button {
    padding: 10px 18px;
    border: 0;
    border-radius: 10px;
    background: var(--sage);
    color: #fff;
    font: inherit;
    cursor: pointer;
  }
  .filters { display: flex; gap: 6px; margin: 18px 0 6px; }
  .filters button {
    padding: 4px 13px;
    border: 1px solid var(--line);
    border-radius: 999px;
    background: transparent;
    color: #5c6a5f;
    font-size: 12px;
    cursor: pointer;
  }
  .filters button.on { background: #e4eee6; border-color: #e4eee6; color: var(--sage-deep); }
  ul { list-style: none; margin: 0; padding: 0; }
  li {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 11px 2px;
    border-bottom: 1px dashed var(--line);
  }
  li .text { flex: 1; }
  li.done .text { color: var(--mute); text-decoration: line-through; }
  li .del {
    padding: 2px 6px;
    border: 0;
    background: transparent;
    color: var(--rose);
    font-size: 12px;
    cursor: pointer;
  }
  .empty { padding: 18px 2px; color: var(--mute); font-size: 13px; }
  .foot {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 14px;
    font-size: 12px;
    color: var(--mute);
  }
  .foot button { border: 0; background: none; color: var(--mute); cursor: pointer; }
</style>
</head>
<body>
<div class="app">
  <h1>待办清单</h1>
  <p class="sub">TODOLIST / 数据驱动视图</p>

  <form id="addForm">
    <input id="todoInput" type="text" maxlength="80" placeholder="今天要做什么?" autocomplete="off">
    <button type="submit">添加</button>
  </form>

  <div class="filters" id="filters">
    <button type="button" data-filter="all" class="on">全部</button>
    <button type="button" data-filter="active">未完成</button>
    <button type="button" data-filter="done">已完成</button>
  </div>

  <ul id="todoList"></ul>

  <div class="foot">
    <span id="counter">共 0 项</span>
    <button type="button" id="clearDone">清除已完成</button>
  </div>
</div>

<script>
  const STORAGE_KEY = 'todolist-demo';
  let todos = load();
  let filter = 'all';

  function load() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      const list = raw ? JSON.parse(raw) : [];
      return Array.isArray(list) ? list : [];
    } catch (err) {
      return [];
    }
  }

  function save() {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
    } catch (err) {
      // 隐私模式或超出配额时,保留内存中的数据
    }
  }

  function visibleTodos() {
    if (filter === 'active') return todos.filter(todo => !todo.done);
    if (filter === 'done') return todos.filter(todo => todo.done);
    return todos;
  }

  function render() {
    const list = document.getElementById('todoList');
    const items = visibleTodos();
    list.innerHTML = '';

    if (items.length === 0) {
      const empty = document.createElement('li');
      empty.className = 'empty';
      empty.textContent = filter === 'all'
        ? '还没有待办,先写一条。'
        : '这个分类下暂时没有内容。';
      list.appendChild(empty);
    }

    items.forEach(todo => {
      const li = document.createElement('li');
      li.dataset.id = todo.id;
      li.className = todo.done ? 'done' : '';

      const box = document.createElement('input');
      box.type = 'checkbox';
      box.checked = todo.done;
      box.dataset.act = 'toggle';

      const text = document.createElement('span');
      text.className = 'text';
      text.textContent = todo.text;

      const del = document.createElement('button');
      del.type = 'button';
      del.className = 'del';
      del.dataset.act = 'del';
      del.textContent = '删除';

      li.append(box, text, del);
      list.appendChild(li);
    });

    const doneCount = todos.filter(todo => todo.done).length;
    document.getElementById('counter').textContent =
      '共 ' + todos.length + ' 项 · 已完成 ' + doneCount + ' 项';
  }

  function commit() {
    save();
    render();
  }

  document.getElementById('addForm').addEventListener('submit', event => {
    event.preventDefault();
    const input = document.getElementById('todoInput');
    const text = input.value.trim();
    if (!text) return;

    const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
    todos = [{ id, text, done: false }, ...todos];
    input.value = '';
    commit();
  });

  document.getElementById('filters').addEventListener('click', event => {
    const btn = event.target.closest('button[data-filter]');
    if (!btn) return;
    filter = btn.dataset.filter;
    btn.parentElement.querySelectorAll('button').forEach(item => {
      item.classList.toggle('on', item === btn);
    });
    render();
  });

  document.getElementById('todoList').addEventListener('change', event => {
    const li = event.target.closest('li[data-id]');
    if (!li || event.target.dataset.act !== 'toggle') return;

    todos = todos.map(todo => {
      return todo.id === li.dataset.id
        ? { ...todo, done: !todo.done }
        : todo;
    });
    commit();
  });

  document.getElementById('todoList').addEventListener('click', event => {
    if (event.target.dataset.act !== 'del') return;
    const li = event.target.closest('li[data-id]');
    if (!li) return;

    todos = todos.filter(todo => todo.id !== li.dataset.id);
    commit();
  });

  document.getElementById('clearDone').addEventListener('click', () => {
    todos = todos.filter(todo => !todo.done);
    commit();
  });

  render();
</script>
</body>
</html>

可以继续优化的方向

  • 双击编辑:把 span.text 临时替换成 input,回车提交、失焦提交、Esc 取消,并做一次非空校验。
  • 筛选写进地址:用 #/active 这样的 hash 保存筛选状态,刷新后仍然停在当前分类,也为第 5 章的 hash 路由做铺垫。
  • 减少重排:先拼好 DocumentFragment 再一次性插入,或只更新发生变化的列表项,避免每次全量重建。
  • 拖拽排序:在 pointerdown 时记录起点,pointermove 时交换数组位置,结束时把新顺序写回存储。
  • 抽出数据层:把 todos 的读写封装成 store,为第 4 章的状态管理库留出接入点,让列表只负责订阅渲染。
筛选与编辑的扩展方式。

筛选已经具备 all、active、done 三种状态,新增分类只需给数据加字段, 在 visibleTodos() 里增加一个分支,按钮继续复用 data-filter 与事件委托,渲染函数不用改。 编辑则从 dblclick 开始:把当前 span 换成 input 并写入原文本, 回车或失焦时提交,Esc 取消;提交前 trim 并校验非空,然后用 todos.map 生成包含新 text 的数组,最后仍然调用 commit()。不要直接改 DOM 文本, 否则刷新后编辑就丢了。

现场演示

下面这个演示把数据放在内存里,刷新页面即清空,用来直观看到“新增 → 渲染 → 勾选 → 删除 → 计数”的闭环。 它和上面的完整代码共用同一套思路,只是省掉了持久化。

现场演示 数据仅保存在当前页面
    共 0 项 · 已完成 0 项
    Chapter 02 / PIXELS

    Canvas 画板

    坐标、路径与像素:用一块画布理解浏览器的即时绘制模型。

    02

    从指针到线条:一个能导出图片的画板

    难度 · 入门进阶

    项目目标

    做一个可以直接画画的小工具:选择颜色与笔触粗细、按住绘制、切换橡皮擦、清空画布、导出 PNG。 界面只保留必要控件,重点放在三件事上:坐标怎么换算、指针事件怎么接、 像素怎么被真正改变。理解了这三点,网格背景、签名板、图片标注都可以在此基础上改出来。

    技术点

    canvas.getContext('2d') devicePixelRatio Pointer Events setPointerCapture destination-out toDataURL

    分步实现

    1. 先把坐标系搭对。canvas 有两套尺寸:HTML 属性 width/height 决定位图的像素网格,CSS 里的 width: 100% 只决定它显示多大。两者不一致时线条会发虚。 按 devicePixelRatio 放大位图,再用 setTransform 缩放回来, 之后所有绘制仍然使用 CSS 像素坐标,在视网膜屏幕上也是清晰的。

      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
      
      function resize() {
        const rect = canvas.getBoundingClientRect();
        const dpr = window.devicePixelRatio || 1;
      
        canvas.width = Math.round(rect.width * dpr);
        canvas.height = Math.round(rect.height * dpr);
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // 坐标仍按 CSS 像素使用
      
        ctx.fillStyle = '#fffdf8';
        ctx.fillRect(0, 0, rect.width, rect.height);
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
      }
    2. 统一用指针事件。鼠标、触控笔、手指都可以触发 pointerdown / pointermove / pointerup。坐标必须减去画布的 getBoundingClientRect() 左上角,才是画布内部坐标。 setPointerCapture 能保证指针移出画布后仍收到 move,不会画到一半断线。

      let drawing = false;
      let last = null;
      
      function pointOf(event) {
        const rect = canvas.getBoundingClientRect();
        return { x: event.clientX - rect.left, y: event.clientY - rect.top };
      }
      
      canvas.addEventListener('pointerdown', event => {
        drawing = true;
        last = pointOf(event);
        canvas.setPointerCapture(event.pointerId);
      });
      
      canvas.addEventListener('pointermove', event => {
        if (!drawing) return;
        const point = pointOf(event);
        stroke(last, point);
        last = point;
      });
      
      canvas.addEventListener('pointerup', () => {
        drawing = false;
        last = null;
      });
      
      canvas.addEventListener('pointercancel', () => {
        drawing = false;
        last = null;
      });
    3. 画“线段”,而不是画“点”。每次拿到新坐标,从上一个点 lineTo 到当前点再 stroke。如果只在每个 move 上画一个圆点, 指针移动快时点与点之间会留下明显的空隙。圆角线帽与圆角连接让转折处更自然。

      function stroke(from, to) {
        ctx.globalCompositeOperation = erasing ? 'destination-out' : 'source-over';
        ctx.strokeStyle = erasing ? '#fffdf8' : document.getElementById('color').value;
        ctx.lineWidth = Number(document.getElementById('size').value);
      
        ctx.beginPath();
        ctx.moveTo(from.x, from.y);
        ctx.lineTo(to.x, to.y);
        ctx.stroke();
      }
    4. 橡皮擦与导出。橡皮擦不是“画一条背景色”,而是把像素擦成透明: 把 globalCompositeOperation 设为 destination-out 即可。 注意 PNG 会保留透明区域,导出前应先在一张临时画布上铺好底色,再把画面盖上去。

      function exportPNG() {
        const out = document.createElement('canvas');
        out.width = canvas.width;
        out.height = canvas.height;
      
        const octx = out.getContext('2d');
        octx.fillStyle = '#fffdf8';
        octx.fillRect(0, 0, out.width, out.height);
        octx.drawImage(canvas, 0, 0);
      
        const link = document.createElement('a');
        link.download = 'drawing.png';
        link.href = out.toDataURL('image/png');
        link.click();
      }
    CSS 尺寸不等于位图尺寸。

    canvas.width / height 是像素网格,CSS 的 width / height 是显示尺寸。只改 CSS 会拉伸位图;只改属性会改变坐标系。两者配合 devicePixelRatio 才是移动端与高分屏的正确做法。

    修改 width/height 会清空画布。

    给 canvas.width 赋值,哪怕数值相同,也会重置整块画布、变换矩阵与绘制状态。 窗口缩放时若要保留内容,需要先用 getImageData 或临时 canvas 备份,再恢复并重绘。 本文示例为了保持代码简短,在 resize 时直接重置。

    完整可运行代码

    保存为 canvas-board.html 后直接打开即可。画布宽度自适应容器,高度固定 360 CSS 像素; 颜色、粗细、橡皮擦与导出都在工具栏里。全部逻辑约一百行,没有引用任何图片或第三方脚本。

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Canvas 画板</title>
    <style>
      body { margin: 0; padding: 24px; background: #f7f4ee; color: #2c352e;
             font: 14px/1.6 "PingFang SC", "Microsoft YaHei", sans-serif; }
      .board { max-width: 720px; margin: 0 auto; }
      .bar { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-bottom: 12px; }
      .bar label { display: flex; align-items: center; gap: 6px; font-size: 13px; color: #5c6a5f; }
      button { padding: 7px 14px; border: 1px solid #c9d3ca; border-radius: 999px;
               background: #fffdf8; color: #4f7a60; font: inherit; cursor: pointer; }
      button.on { background: #7ba58a; border-color: #7ba58a; color: #fff; }
      canvas { display: block; width: 100%; height: 360px; background: #fffdf8;
               border: 1px solid #d8ded8; border-radius: 12px;
               touch-action: none; cursor: crosshair; }
      .hint { margin-top: 10px; font-size: 12px; color: #8b968c; }
    </style>
    </head>
    <body>
    <div class="board">
      <div class="bar">
        <label>颜色 <input type="color" id="color" value="#4f7a60"></label>
        <label>粗细 <input type="range" id="size" min="1" max="24" value="4"></label>
        <button id="eraser" type="button">橡皮擦</button>
        <button id="clear" type="button">清空</button>
        <button id="save" type="button">导出 PNG</button>
      </div>
      <canvas id="canvas" width="720" height="360"></canvas>
      <p class="hint">按住鼠标或手指绘制;橡皮擦按钮可切换模式。</p>
    </div>
    
    <script>
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
      const BG = '#fffdf8';
      let drawing = false;
      let erasing = false;
      let last = null;
    
      // 位图按设备像素比放大,绘制坐标仍使用 CSS 像素
      function resize() {
        const rect = canvas.getBoundingClientRect();
        const dpr = window.devicePixelRatio || 1;
        canvas.width = Math.round(rect.width * dpr);
        canvas.height = Math.round(rect.height * dpr);
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        ctx.fillStyle = BG;
        ctx.fillRect(0, 0, rect.width, rect.height);
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
      }
    
      function pointOf(event) {
        const rect = canvas.getBoundingClientRect();
        return { x: event.clientX - rect.left, y: event.clientY - rect.top };
      }
    
      function stroke(from, to) {
        ctx.globalCompositeOperation = erasing ? 'destination-out' : 'source-over';
        ctx.strokeStyle = erasing ? BG : document.getElementById('color').value;
        ctx.lineWidth = Number(document.getElementById('size').value);
        ctx.beginPath();
        ctx.moveTo(from.x, from.y);
        ctx.lineTo(to.x, to.y);
        ctx.stroke();
      }
    
      function start(event) {
        drawing = true;
        last = pointOf(event);
        canvas.setPointerCapture(event.pointerId);
        stroke(last, last); // 单击也留下一个圆点
      }
    
      function move(event) {
        if (!drawing) return;
        const point = pointOf(event);
        stroke(last, point);
        last = point;
      }
    
      function end(event) {
        drawing = false;
        last = null;
        if (canvas.hasPointerCapture(event.pointerId)) {
          canvas.releasePointerCapture(event.pointerId);
        }
      }
    
      canvas.addEventListener('pointerdown', start);
      canvas.addEventListener('pointermove', move);
      canvas.addEventListener('pointerup', end);
      canvas.addEventListener('pointercancel', end);
    
      document.getElementById('eraser').addEventListener('click', function () {
        erasing = !erasing;
        this.classList.toggle('on', erasing);
      });
    
      document.getElementById('clear').addEventListener('click', function () {
        const rect = canvas.getBoundingClientRect();
        ctx.globalCompositeOperation = 'source-over';
        ctx.fillStyle = BG;
        ctx.fillRect(0, 0, rect.width, rect.height);
      });
    
      document.getElementById('save').addEventListener('click', function () {
        // destination-out 擦出的区域是透明像素,导出前先铺一层底色
        const out = document.createElement('canvas');
        out.width = canvas.width;
        out.height = canvas.height;
        const octx = out.getContext('2d');
        octx.fillStyle = BG;
        octx.fillRect(0, 0, out.width, out.height);
        octx.drawImage(canvas, 0, 0);
    
        const link = document.createElement('a');
        link.download = 'canvas-' + Date.now() + '.png';
        link.href = out.toDataURL('image/png');
        link.click();
      });
    
      window.addEventListener('resize', function () {
        resize(); // 简化处理:尺寸变化会清空画布
      });
    
      resize();
    </script>
    </body>
    </html>

    可以继续优化的方向

    • 撤销与重做:每次落笔记录 { from, to, color, size, erasing },撤销时整幅重绘;也可以按步保存 ImageData,但更占内存。
    • 压感与速度:读取 event.pressure 或根据两点距离动态调整 lineWidth,能模拟毛笔的轻重变化。
    • 形状工具:在 pointerdown 时记录起点,move 时用临时画布预览矩形/圆形,up 时落定。
    • 本地保存:toDataURL 的字符串很大,适合放 IndexedDB;localStorage 通常只有约 5MB,画几笔就可能写不进去。
    • 窗口缩放保内容:resize 前先把当前画面画进临时 canvas,重设尺寸后再 drawImage 回来,避免用户作品被清空。
    Chapter 03 / DATA TO SHAPE

    数据可视化:从零实现柱状图

    不引入图表库,用 SVG 把数字映射成几何图形,并补上动画、交互与响应式。

    03

    比例尺、坐标与生长动画

    难度 · 进阶

    项目目标

    给一组「月份 → 访问量」的数据,画出带坐标轴、网格、数值标签与 tooltip 的柱状图; 进入页面时柱子从底部生长,窗口变窄时整张图等比缩放。整个实现不依赖 ECharts、D3 或任何图表库, 只使用 SVG 元素与浏览器原生 API。

    图表库真正替我们做的,核心只有两件事:把数据域映射到像素域, 以及在数据变化时同步图形。把这两件事亲手写一遍,再回头看任何图表库的配置项都会清楚很多。

    技术点

    SVG viewBox createElementNS 线性比例尺 requestAnimationFrame easeOutCubic tooltip 定位

    分步实现

    1. 先留白,再算比例尺。外框尺寸减去四边 padding,得到真正画图的内绘图区。 纵轴最大值乘以 1.1,给顶部留一点余量,柱子不会顶到边框。注意 SVG 的 y 轴向下增长, 所以“柱顶”是计算出来的 y,“柱底”是 y + height。

      const W = 640;
      const H = 340;
      const pad = { top: 28, right: 18, bottom: 46, left: 46 };
      const innerW = W - pad.left - pad.right;
      const innerH = H - pad.top - pad.bottom;
      
      const maxValue = Math.max(...data.map(item => item.value)) * 1.1;
      const band = innerW / data.length;             // 每根柱占用的带宽
      const barW = Math.min(56, band * 0.56);        // 柱子本身更窄一些
      
      const yOf = value => pad.top + innerH - (value / maxValue) * innerH;
      量计算方式说明
      内绘图区宽W - pad.left - pad.right坐标系实际可用宽度
      单柱带宽innerW / data.length含柱间空隙
      柱宽Math.min(56, band * 0.56)限制最大宽度,避免柱子过胖
      柱顶 ypad.top + innerH - value / maxValue * innerH值越大,y 越小
      柱高pad.top + innerH - y从柱顶到底线
    2. 用 createElementNS 创建 SVG 元素。 SVG 属于另一个命名空间,document.createElement('rect') 创建出来的是未知 HTML 元素, 浏览器不会把它当图形渲染。所有属性通过 setAttribute 设置,包括 fill、 rx 这类看起来像 CSS 的属性。

      const NS = 'http://www.w3.org/2000/svg';
      
      function el(name, attrs) {
        const node = document.createElementNS(NS, name);
        for (const key in attrs) {
          node.setAttribute(key, attrs[key]);
        }
        return node;
      }
      
      const rect = el('rect', {
        x: pad.left + index * band + (band - barW) / 2,
        y: pad.top + innerH,
        width: barW,
        height: 0,
        rx: 6,
        fill: '#7ba58a'
      });
      svg.appendChild(rect);
    3. 用 rAF 做生长动画。不要用 CSS 过渡去改 SVG 的 y 与 height 属性, 属性变化不触发 CSS transition。用 requestAnimationFrame 每帧计算进度, 再写入属性最直接。缓动函数 1 - (1 - t)³ 让动画起步快、收尾慢,观感更自然。

      function grow(rect, label, targetHeight, duration) {
        const started = performance.now();
      
        function frame(now) {
          const t = Math.min(1, (now - started) / duration);
          const k = 1 - Math.pow(1 - t, 3); // easeOutCubic
          const height = targetHeight * k;
      
          rect.setAttribute('height', height);
          rect.setAttribute('y', pad.top + innerH - height);
      
          if (t < 1) {
            requestAnimationFrame(frame);
          } else {
            label.setAttribute('opacity', 1); // 动画结束再显示数值
          }
        }
      
        requestAnimationFrame(frame);
      }
    4. tooltip 用绝对定位,坐标从 DOM 读取。把 tooltip 放在与图表同级的 position: relative 容器里,再用柱子的 getBoundingClientRect() 减去容器的矩形,得到相对位置。这样即使 SVG 被 viewBox 缩放,tooltip 仍然贴着柱子。

      rect.addEventListener('pointerenter', function () {
        tooltip.textContent = item.label + ':' + item.value;
        tooltip.style.opacity = '1';
      });
      
      rect.addEventListener('pointermove', function () {
        const barBox = rect.getBoundingClientRect();
        const chartBox = chart.getBoundingClientRect();
      
        tooltip.style.left = (barBox.left - chartBox.left + barBox.width / 2) + 'px';
        tooltip.style.top = (barBox.top - chartBox.top) + 'px';
      });
      
      rect.addEventListener('pointerleave', function () {
        tooltip.style.opacity = '0';
      });
    响应式的两种做法。

    示例使用固定 viewBox="0 0 640 340" 加 width: 100%,整张图等比缩放, 实现最简单。若希望小屏时字号不变、柱子重新排布,就需要监听容器尺寸,按新的宽度重新计算比例尺并重绘。 数据量不大时,重绘的成本远低于维护一套复杂的缩放逻辑。

    完整可运行代码

    保存为 bar-chart.html 后打开即可。数据写在脚本顶部的 data 数组里, 修改数值或增删月份,图表会自动重算柱宽、比例与标签位置。悬停柱子可以看到具体数值。

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>手写柱状图</title>
    <style>
      body {
        margin: 0;
        padding: 48px 18px;
        background: #f7f4ee;
        color: #2c352e;
        font: 14px/1.6 "PingFang SC", "Microsoft YaHei", sans-serif;
      }
      .wrap {
        max-width: 720px;
        margin: 0 auto;
        padding: 24px 20px 16px;
        background: #fffdf8;
        border: 1px solid #dfe3db;
        border-radius: 16px;
      }
      h1 { margin: 0 0 4px; font-size: 20px; }
      .sub { margin: 0 0 18px; font-size: 11px; letter-spacing: 0.16em; color: #8b968c; }
      .chart { position: relative; }
      .chart svg { display: block; width: 100%; height: auto; overflow: visible; }
      .tooltip {
        position: absolute;
        padding: 4px 9px;
        border-radius: 6px;
        background: #25312a;
        color: #e6eee7;
        font-size: 12px;
        white-space: nowrap;
        opacity: 0;
        pointer-events: none;
        transform: translate(-50%, -130%);
        transition: opacity 0.15s ease;
      }
    </style>
    </head>
    <body>
    <div class="wrap">
      <h1>月度访问量</h1>
      <p class="sub">SVG / 手写比例尺</p>
      <div class="chart" id="chart">
        <svg id="svg" viewBox="0 0 640 340" role="img" aria-label="月度访问量柱状图"></svg>
        <div class="tooltip" id="tooltip"></div>
      </div>
    </div>
    
    <script>
      const data = [
        { label: '一月', value: 120 },
        { label: '二月', value: 168 },
        { label: '三月', value: 96 },
        { label: '四月', value: 214 },
        { label: '五月', value: 182 },
        { label: '六月', value: 245 }
      ];
    
      const W = 640;
      const H = 340;
      const pad = { top: 28, right: 18, bottom: 46, left: 46 };
      const innerW = W - pad.left - pad.right;
      const innerH = H - pad.top - pad.bottom;
      const maxValue = Math.max(...data.map(item => item.value)) * 1.1;
      const band = innerW / data.length;
      const barW = Math.min(56, band * 0.56);
      const NS = 'http://www.w3.org/2000/svg';
    
      const svg = document.getElementById('svg');
      const chart = document.getElementById('chart');
      const tooltip = document.getElementById('tooltip');
    
      function el(name, attrs) {
        const node = document.createElementNS(NS, name);
        for (const key in attrs) {
          node.setAttribute(key, attrs[key]);
        }
        return node;
      }
    
      function yOf(value) {
        return pad.top + innerH - (value / maxValue) * innerH;
      }
    
      function drawAxes() {
        svg.appendChild(el('line', {
          x1: pad.left,
          y1: pad.top + innerH,
          x2: pad.left + innerW,
          y2: pad.top + innerH,
          stroke: '#c9d3ca',
          'stroke-width': 1
        }));
    
        for (let i = 0; i <= 4; i++) {
          const value = (maxValue / 4) * i;
          const y = yOf(value);
    
          svg.appendChild(el('line', {
            x1: pad.left,
            y1: y,
            x2: pad.left + innerW,
            y2: y,
            stroke: '#e4e8e2',
            'stroke-width': 1,
            'stroke-dasharray': i === 0 ? '0' : '3 5'
          }));
    
          const tick = el('text', {
            x: pad.left - 10,
            y: y + 4,
            'text-anchor': 'end',
            fill: '#8b968c',
            'font-size': 11
          });
          tick.textContent = Math.round(value);
          svg.appendChild(tick);
        }
      }
    
      function drawBars() {
        data.forEach((item, index) => {
          const x = pad.left + index * band + (band - barW) / 2;
          const targetY = yOf(item.value);
          const targetH = pad.top + innerH - targetY;
    
          const rect = el('rect', {
            x: x,
            y: pad.top + innerH,
            width: barW,
            height: 0,
            rx: 6,
            fill: index % 2 === 0 ? '#7ba58a' : '#e3a98f'
          });
          svg.appendChild(rect);
    
          const valueText = el('text', {
            x: x + barW / 2,
            y: targetY - 8,
            'text-anchor': 'middle',
            fill: '#5c6a5f',
            'font-size': 11,
            opacity: 0
          });
          valueText.textContent = item.value;
          svg.appendChild(valueText);
    
          const label = el('text', {
            x: x + barW / 2,
            y: pad.top + innerH + 22,
            'text-anchor': 'middle',
            fill: '#8b968c',
            'font-size': 12
          });
          label.textContent = item.label;
          svg.appendChild(label);
    
          grow(rect, valueText, targetH);
    
          rect.style.cursor = 'pointer';
          rect.addEventListener('pointerenter', () => {
            tooltip.textContent = item.label + ':' + item.value;
            tooltip.style.opacity = '1';
          });
          rect.addEventListener('pointermove', () => {
            const barBox = rect.getBoundingClientRect();
            const chartBox = chart.getBoundingClientRect();
            tooltip.style.left = (barBox.left - chartBox.left + barBox.width / 2) + 'px';
            tooltip.style.top = (barBox.top - chartBox.top) + 'px';
          });
          rect.addEventListener('pointerleave', () => {
            tooltip.style.opacity = '0';
          });
        });
      }
    
      function grow(rect, label, targetH) {
        const started = performance.now();
        const duration = 720;
    
        function frame(now) {
          const t = Math.min(1, (now - started) / duration);
          const k = 1 - Math.pow(1 - t, 3);
          const h = targetH * k;
    
          rect.setAttribute('height', h);
          rect.setAttribute('y', pad.top + innerH - h);
    
          if (t < 1) {
            requestAnimationFrame(frame);
          } else {
            label.setAttribute('opacity', 1);
          }
        }
    
        requestAnimationFrame(frame);
      }
    
      drawAxes();
      drawBars();
    </script>
    </body>
    </html>

    可以继续优化的方向

    • 多系列:把 band 再均分给每组数据,实现分组柱状图;或把第二组叠在第一组上,做成堆叠柱状图。
    • 抽象比例尺:抽出 scaleLinear(domain, range),统一处理负数、对数轴与刻度生成,后续折线图、散点图可以直接复用。
    • 响应式重绘:用 ResizeObserver 监听容器宽度,按新宽度重新计算 band 与字号,而不是整体缩放。
    • 无障碍:给每根柱子加 <title> 或 aria-label,让读屏软件也能读出数值。
    • 大数据量:上千根柱子时 DOM 节点会成为瓶颈,可以改用 Canvas 绘制,交互则依赖命中检测。
    Chapter 04 / STATE

    迷你状态管理库

    用发布订阅与不可变更新,写一个三十行核心代码的 createStore。

    04

    getState / setState / subscribe 与 selector

    难度 · 高阶

    项目目标

    实现一个可以真正用起来的小型状态容器:getState() 读取快照,setState() 更新状态,subscribe() 订阅变化并返回取消订阅函数;在此基础上增加 selector 精准订阅与 batch 批量通知。最后用一个计数器界面验证: 状态变化时,只有关心该字段的订阅者被触发。

    Redux、Zustand、Pinia 的实现细节各不相同,但核心模型都可以压缩成一句话: 把状态放进闭包,把变更收进唯一入口,把通知交给订阅者。 自己写一遍,再读这些库的源码会轻松很多。

    技术点

    闭包 发布订阅 不可变更新 Object.is Set 批量通知

    分步实现

    1. 核心只有三个方法。状态与监听器都保存在闭包里,外部只能通过返回的对象操作。 setState 接受对象或函数:函数形式能拿到最新状态,避免连续更新时读到旧值。 每次先合并出 next,逐键比较;完全没变化就提前返回,不触发任何通知。

      function createStore(initialState) {
        let state = initialState;
        const listeners = new Set();
      
        function getState() {
          return state;
        }
      
        function setState(patch) {
          const partial = typeof patch === 'function' ? patch(state) : patch;
          const next = Object.assign({}, state, partial);
      
          const changed = Object.keys(next).some(function (key) {
            return !Object.is(next[key], state[key]);
          });
          if (!changed) return state; // 没有变化就不通知
      
          state = next;
          Array.from(listeners).forEach(function (listener) {
            listener(state);
          });
          return state;
        }
      
        function subscribe(listener) {
          listeners.add(listener);
          return function unsubscribe() {
            listeners.delete(listener);
          };
        }
      
        return { getState, setState, subscribe };
      }
    2. 用 selector 做精准订阅。组件往往只关心状态中的一小块。 select 在订阅时记录一次选中值,之后每次通知都重新计算; 只有 Object.is 判定为变化时才调用监听器。 这也意味着 selector 必须返回稳定值:每次返回新对象或新数组,都会被认为“变了”。

      function select(store, selector, listener) {
        let current = selector(store.getState());
      
        return store.subscribe(function (state) {
          const next = selector(state);
          if (Object.is(next, current)) return; // 选中值没变,跳过
      
          const previous = current;
          current = next;
          listener(next, previous);
        });
      }
      
      // 只关心 count,不关心 step
      select(store, state => state.count, function (count, previous) {
        console.log('count', previous, '->', count);
      });
    3. batch 把多次更新合并成一次通知。用一个深度计数器记录当前是否处于批次中。 批次内调用 setState 时只把 dirty 标记为真,不立即通知; 最外层批次结束时再统一通知一次。注意用 try/finally,即使回调抛错也能正确收尾。

      let batchDepth = 0;
      let dirty = false;
      
      function notify() {
        if (batchDepth > 0) {
          dirty = true; // 先记账,等批次结束再统一通知
          return;
        }
        Array.from(listeners).forEach(function (listener) {
          listener(state);
        });
      }
      
      function batch(fn) {
        batchDepth += 1;
        try {
          fn();
        } finally {
          batchDepth -= 1;
          if (batchDepth === 0 && dirty) {
            dirty = false;
            notify(); // 此时 batchDepth 已归零,会真正执行通知
          }
        }
      }
    4. 通知顺序是同步的、按注册顺序执行的。这意味着监听器里不能假设 DOM 已经更新完, 也不要在监听器里做耗时操作。下面的输出顺序可以帮助理解:取消订阅后,监听器不会再被调用。

      const store = createStore({ n: 0 });
      const offA = store.subscribe(state => console.log('A', state.n));
      const offB = store.subscribe(state => console.log('B', state.n));
      
      store.setState({ n: 1 }); // 输出 A 1、B 1
      offB();                   // 取消 B 的订阅
      store.setState({ n: 2 }); // 只输出 A 2
    不可变更新的意义。

    setState 通过浅合并生成新对象,旧状态保持不变。这让比较变得便宜:只要引用没变, 就认为这一块没有变化;也让时间旅行、撤销重做、React 的浅比较优化成为可能。 代价是深层嵌套时要逐层展开,或者引入 Immer 这类结构共享工具。

    不要原地修改状态。

    state.count += 1 之后再 return state,引用没有变化, 基于 Object.is 的订阅者会认为什么都没发生。正确做法是返回一个新对象。

    // 错误:原地修改,订阅者可能收不到通知
    store.setState(state => {
      state.count += 1;
      return state;
    });
    
    // 正确:返回新对象
    store.setState(state => ({ count: state.count + 1 }));

    完整可运行代码

    保存为 mini-store.html 后打开。页面上有加一、减一与批量重置三个操作; “计数”只订阅 count,“摘要”订阅 count + step 的组合字符串。 点击批量重置时,两次 setState 只会触发一轮 DOM 更新。

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>迷你状态管理</title>
    <style>
      body {
        margin: 0;
        padding: 48px 18px;
        min-height: 100vh;
        background: #f7f4ee;
        color: #2c352e;
        font: 15px/1.7 "PingFang SC", "Microsoft YaHei", sans-serif;
      }
      .app {
        max-width: 480px;
        margin: 0 auto;
        padding: 28px 26px;
        background: #fffdf8;
        border: 1px solid #dfe3db;
        border-radius: 18px;
      }
      h1 { margin: 0 0 4px; font-size: 22px; }
      .sub { margin: 0 0 24px; color: #8b968c; font-size: 11px; letter-spacing: 0.16em; }
      .summary {
        padding: 12px 14px;
        border: 1px dashed #c9d3ca;
        border-radius: 10px;
        color: #5c6a5f;
        font-size: 13px;
      }
      .counter {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 18px;
        margin: 24px 0;
      }
      .counter strong {
        min-width: 90px;
        font-size: 46px;
        font-weight: 500;
        color: #4f7a60;
        text-align: center;
        font-variant-numeric: tabular-nums;
      }
      button {
        padding: 8px 18px;
        border: 1px solid #c9d3ca;
        border-radius: 999px;
        background: #fffdf8;
        color: #4f7a60;
        font: inherit;
        cursor: pointer;
      }
      button:hover { background: #e4eee6; }
      .log { min-height: 20px; color: #8b968c; font-size: 12px; text-align: center; }
      .reset { display: block; margin: 18px auto 0; font-size: 12px; }
    </style>
    </head>
    <body>
    <div class="app">
      <h1>迷你状态管理</h1>
      <p class="sub">CREATE STORE / 单向数据流</p>
    
      <p class="summary" id="summary">…</p>
    
      <div class="counter">
        <button type="button" id="dec">减一</button>
        <strong id="count">0</strong>
        <button type="button" id="inc">加一</button>
      </div>
    
      <p class="log" id="log">等待操作</p>
      <button class="reset" type="button" id="reset">批量重置(一次通知)</button>
    </div>
    
    <script>
      // ---------- 1. 核心:createStore ----------
      function createStore(initialState) {
        let state = initialState;
        const listeners = new Set();
        let batchDepth = 0;
        let dirty = false;
    
        function notify() {
          if (batchDepth > 0) {
            dirty = true;
            return;
          }
          // 复制一份,允许监听器在回调中取消订阅
          Array.from(listeners).forEach(function (listener) {
            listener(state);
          });
        }
    
        function getState() {
          return state;
        }
    
        function setState(patch) {
          const partial = typeof patch === 'function' ? patch(state) : patch;
          const next = Object.assign({}, state, partial);
    
          const changed = Object.keys(next).some(function (key) {
            return !Object.is(next[key], state[key]);
          });
          if (!changed) return state;
    
          state = next;
          notify();
          return state;
        }
    
        function subscribe(listener) {
          listeners.add(listener);
          return function unsubscribe() {
            listeners.delete(listener);
          };
        }
    
        function batch(fn) {
          batchDepth += 1;
          try {
            fn();
          } finally {
            batchDepth -= 1;
            if (batchDepth === 0 && dirty) {
              dirty = false;
              notify();
            }
          }
        }
    
        return { getState, setState, subscribe, batch };
      }
    
      // ---------- 2. selector:只在选中值变化时回调 ----------
      function select(store, selector, listener) {
        let current = selector(store.getState());
    
        return store.subscribe(function (state) {
          const next = selector(state);
          if (Object.is(next, current)) return;
    
          const previous = current;
          current = next;
          listener(next, previous);
        });
      }
    
      // ---------- 3. 接入界面 ----------
      const store = createStore({ count: 0, step: 1 });
      const $ = function (id) {
        return document.getElementById(id);
      };
    
      // 首次渲染:订阅只负责后续变化
      function paint() {
        const state = store.getState();
        $('count').textContent = state.count;
        $('summary').textContent = '计数 ' + state.count + ' · 步长 ' + state.step;
      }
      paint();
    
      select(store, function (state) {
        return state.count;
      }, function (count, previous) {
        $('count').textContent = count;
        $('log').textContent = 'count: ' + previous + ' → ' + count;
      });
    
      select(store, function (state) {
        return '计数 ' + state.count + ' · 步长 ' + state.step;
      }, function (text) {
        $('summary').textContent = text;
      });
    
      $('inc').addEventListener('click', function () {
        store.setState(function (state) {
          return { count: state.count + state.step };
        });
      });
    
      $('dec').addEventListener('click', function () {
        store.setState(function (state) {
          return { count: state.count - state.step };
        });
      });
    
      $('reset').addEventListener('click', function () {
        store.batch(function () {
          store.setState({ count: 0 });
          store.setState({ step: 1 });
        });
        $('log').textContent = '批量更新完成:只通知一次';
      });
    </script>
    </body>
    </html>

    原理拆解:一次 setState 经历了什么

    阶段动作要点
    1. 计算补丁对象直接合并,函数则先调用拿到返回值函数式更新基于最新 state,避免闭包旧值
    2. 生成新状态Object.assign({}, state, partial)浅合并,不修改原对象
    3. 变化检测逐键 Object.is 比较没有变化就提前返回
    4. 写入闭包state = next唯一的状态写入口
    5. 同步通知遍历监听器快照按注册顺序执行,可能触发 selector 比较
    6. 更新视图监听器内写 DOMDOM 更新由订阅者自行负责

    可以继续优化的方向

    • 中间件:把 setState 包装成可组合的高阶函数,加入日志、持久化、防抖等横切逻辑。
    • 嵌套更新:提供 update(path, updater),逐层复制路径上的对象,保持结构共享。
    • 开发期冻结:在开发环境对 next 执行深层 Object.freeze,让原地修改尽早暴露。
    • 接入框架:React 中可用 useSyncExternalStore 订阅,保证并发渲染下读到一致快照。
    • 持久化:订阅整个 store,把序列化后的状态写入 localStorage;注意版本号与迁移逻辑。
    Chapter 05 / ROUTING

    极简 SPA 路由

    用 hash 与路由表做一个不刷新页面的多视图应用,并正确清理副作用。

    05

    hashchange、动态参数与视图生命周期

    难度 · 进阶

    项目目标

    做一个只有三个页面 + 一个 404 的单页应用:首页、关于、文章详情(#/post/42)。 要求支持浏览器前进后退、地址可直接分享、动态参数解析,并且在离开某个页面时销毁它留下的定时器或事件监听。 整个路由核心不超过八十行,但已经具备真实项目里最常用的能力。

    技术点

    hashchange 路由表 动态参数 正则匹配 URLSearchParams 副作用清理

    分步实现

    1. 为什么先用 hash。修改 location.hash 不会向服务器发起请求, 浏览器却会记录一条历史记录,并触发 hashchange。这意味着前进、后退、刷新、复制链接都能正常工作, 而且不需要服务端配置。代价是地址里会多一个 #。 history.pushState 更干净,但刷新与直接访问时需要服务端把所有路径回退到同一个 HTML。

      function parseHash() {
        const raw = location.hash.slice(1) || '/';
        const parts = raw.split('?');
      
        return {
          path: parts[0] || '/',
          query: new URLSearchParams(parts[1] || '')
        };
      }
      
      // #/post/42?from=list
      // path  -> '/post/42'
      // query -> URLSearchParams { 'from' => 'list' }
    2. 把动态参数编译成正则。路由表里写 /post/:id, 渲染前把 :id 替换成捕获组 ([^/]+),再用 match 匹配当前路径。捕获到的值要 decodeURIComponent, 因为地址栏里的中文与特殊字符会被编码。

      function matchPath(pattern, path) {
        const names = [];
        const source = pattern.replace(/:([^/]+)/g, function (_, name) {
          names.push(name);
          return '([^/]+)';
        });
      
        const result = path.match(new RegExp('^' + source + '$'));
        if (!result) return null;
      
        const params = {};
        names.forEach(function (name, index) {
          params[name] = decodeURIComponent(result[index + 1]);
        });
        return params;
      }
      
      matchPath('/post/:id', '/post/42'); // { id: '42' }
      matchPath('/post/:id', '/about');   // null
    3. 视图返回清理函数。切换路由时,先把上一个视图的清理函数执行掉,再清空容器、渲染新视图。 任何在视图里创建的定时器、window 监听、WebSocket、动画帧,都应该在清理函数里释放。 忘记清理是单页应用最常见的内存泄漏来源。

      function render() {
        const { path, query } = parseHash();
      
        // 1. 销毁上一个视图的副作用
        if (typeof cleanup === 'function') {
          cleanup();
          cleanup = null;
        }
      
        // 2. 查路由表
        let matched = null;
        let params = {};
        for (const route of routes) {
          const result = matchPath(route.path, path);
          if (result) {
            matched = route;
            params = result;
            break;
          }
        }
      
        // 3. 渲染或回退到 404
        outlet.innerHTML = '';
        if (!matched) {
          renderNotFound(path);
          return;
        }
      
        const stop = matched.view({ params, query, outlet });
        if (typeof stop === 'function') cleanup = stop;
      }
    4. 导航高亮与 404。根据当前 path 给对应链接加类名; 未知路径不要静默失败,渲染一个 404 视图,同时保留导航,用户还能点回去。 路径来自用户输入,写入 DOM 时优先用 textContent,不要直接拼进 innerHTML。

      function highlight(path) {
        document.querySelectorAll('#nav a').forEach(function (link) {
          const target = (link.getAttribute('href') || '').replace('#', '');
          link.classList.toggle('on', target === path);
        });
      }
      
      function renderNotFound(path) {
        outlet.innerHTML = '<h2>404</h2>';
      
        const p = document.createElement('p');
        p.append('没有找到 ');
        const code = document.createElement('code');
        code.textContent = path;
        p.append(code, ' 对应的页面。');
        outlet.appendChild(p);
      
        highlight(path);
      }
    首次进入不会触发 hashchange。

    页面加载完成时,浏览器只读取当前 hash,不会因为“有了 hash”而派发事件。 所以必须在绑定监听之后手动调用一次 render(),否则直接打开 index.html#/post/42 会看到空白。

    hash 路由与 History 路由。

    hash 路由不依赖服务端,适合静态站点与离线文件;History 路由地址更自然, 但需要服务端把所有未匹配的路径回退到入口 HTML。两者的渲染模型相同: 监听地址变化 → 匹配路由 → 清理旧视图 → 渲染新视图。

    完整可运行代码

    保存为 mini-router.html 后打开即可。点击“文章 42”会进入详情页,页面里的时钟每秒更新; 切到其他页面后定时器会被清理,可以在开发者工具的 Performance 面板里验证它没有继续运行。 把地址改成 #/post/7 再刷新,也能直接进入对应文章。

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>极简 hash 路由</title>
    <style>
      body {
        margin: 0;
        padding: 48px 18px;
        background: #f7f4ee;
        color: #2c352e;
        font: 15px/1.7 "PingFang SC", "Microsoft YaHei", sans-serif;
      }
      .app {
        max-width: 620px;
        margin: 0 auto;
        padding: 26px 28px 32px;
        background: #fffdf8;
        border: 1px solid #dfe3db;
        border-radius: 18px;
      }
      h1 { margin: 0 0 6px; font-size: 22px; }
      nav { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 22px; }
      nav a {
        padding: 5px 13px;
        border: 1px solid #dfe3db;
        border-radius: 999px;
        color: #5c6a5f;
        font-size: 13px;
        text-decoration: none;
      }
      nav a.on { background: #e4eee6; border-color: #e4eee6; color: #4f7a60; font-weight: 600; }
      #outlet {
        min-height: 190px;
        padding: 18px 20px;
        border: 1px dashed #c9d3ca;
        border-radius: 12px;
      }
      #outlet p { color: #5c6a5f; }
      #outlet code {
        padding: 1px 6px;
        border-radius: 5px;
        background: #e4eee6;
        color: #4f7a60;
      }
      .clock { font-family: Consolas, monospace; color: #4f7a60; }
    </style>
    </head>
    <body>
    <div class="app">
      <h1>极简 SPA 路由</h1>
      <nav id="nav">
        <a href="#/">首页</a>
        <a href="#/about">关于</a>
        <a href="#/post/42">文章 42</a>
        <a href="#/missing">坏链接</a>
      </nav>
      <main id="outlet"></main>
    </div>
    
    <script>
      const outlet = document.getElementById('outlet');
      let cleanup = null;
    
      const routes = [
        {
          path: '/',
          view: function () {
            outlet.innerHTML = '<h2>首页</h2>' +
              '<p>点击上方链接切换视图,地址栏的 hash 同步变化,页面不会刷新。</p>';
          }
        },
        {
          path: '/about',
          view: function () {
            outlet.innerHTML = '<h2>关于</h2>' +
              '<p>这是一个不依赖框架的 hash 路由,路由表、参数匹配与清理逻辑都写在同一个文件里。</p>';
          }
        },
        {
          path: '/post/:id',
          view: function (context) {
            outlet.innerHTML = '<h2></h2>' +
              '<p>当前时间:<span class="clock" id="clock">--:--:--</span></p>' +
              '<p>离开本页时,下面的定时器会被清理,不会在后台继续运行。</p>';
    
            // 动态参数用 textContent 写入,避免被当成 HTML
            outlet.querySelector('h2').textContent = '文章 ' + context.params.id;
    
            const timer = setInterval(function () {
              const el = document.getElementById('clock');
              if (el) el.textContent = new Date().toLocaleTimeString('zh-CN');
            }, 1000);
    
            return function () {
              clearInterval(timer);
            };
          }
        }
      ];
    
      function parseHash() {
        const raw = location.hash.slice(1) || '/';
        const parts = raw.split('?');
        return {
          path: parts[0] || '/',
          query: new URLSearchParams(parts[1] || '')
        };
      }
    
      function matchPath(pattern, path) {
        const names = [];
        const source = pattern.replace(/:([^/]+)/g, function (_, name) {
          names.push(name);
          return '([^/]+)';
        });
    
        const result = path.match(new RegExp('^' + source + '$'));
        if (!result) return null;
    
        const params = {};
        names.forEach(function (name, index) {
          params[name] = decodeURIComponent(result[index + 1]);
        });
        return params;
      }
    
      function highlight(path) {
        document.querySelectorAll('#nav a').forEach(function (link) {
          const target = (link.getAttribute('href') || '').replace('#', '');
          link.classList.toggle('on', target === path);
        });
      }
    
      function renderNotFound(path) {
        outlet.innerHTML = '<h2>404</h2>';
    
        const p = document.createElement('p');
        p.append('没有找到 ');
        const code = document.createElement('code');
        code.textContent = path;
        p.append(code, ' 对应的页面。');
        outlet.appendChild(p);
    
        highlight(path);
      }
    
      function render() {
        const routeInfo = parseHash();
    
        // 1. 先清理上一个视图留下的副作用
        if (typeof cleanup === 'function') {
          cleanup();
          cleanup = null;
        }
    
        // 2. 在路由表中查找匹配项
        let matched = null;
        let params = {};
        for (const route of routes) {
          const result = matchPath(route.path, routeInfo.path);
          if (result) {
            matched = route;
            params = result;
            break;
          }
        }
    
        // 3. 渲染
        outlet.innerHTML = '';
        if (!matched) {
          renderNotFound(routeInfo.path);
          return;
        }
    
        const stop = matched.view({
          params: params,
          query: routeInfo.query,
          outlet: outlet
        });
        if (typeof stop === 'function') cleanup = stop;
    
        highlight(routeInfo.path);
      }
    
      window.addEventListener('hashchange', render);
      render(); // 首次进入不会触发 hashchange,需要手动渲染一次
    </script>
    </body>
    </html>

    可以继续优化的方向

    • 路由守卫:在渲染前执行一组 beforeEach 函数,用于登录校验、权限判断或重定向。
    • 懒加载视图:视图函数改为动态 import(),首次访问某个路由时才加载对应模块。
    • 滚动恢复:切换路由时记录 scrollY,后退时恢复;新页面则滚动到顶部。
    • 拦截链接点击:用 document.addEventListener('click') 判断 a[href^="#/"],统一处理修饰键与新标签页行为。
    • History 模式:把 hash 换成 history.pushState,同时监听 popstate,并配置服务端回退规则。