💡

在本文中,我将结合代码讲解我在 Astro 博客中实现的各项 UX 功能。

前言

为了提升博客的用户体验,我实现了以下 10 项功能。

功能说明
保存阅读进度下次访问时可从上次停下的位置继续阅读
悬浮分享按钮移动端一键分享
代码复制按钮为代码块添加快速复制功能
键盘快捷键通过 Cmd+K 快速跳转至搜索
Toast 气泡通知操作反馈的视觉提示
阅读进度条可视化当前文章的阅读进度
目录滚动追踪 (Scrollspy)高亮显示当前正在阅读的章节
打印专用样式针对文章打印进行的样式优化
深色模式支持通过 CSS 变量实现的皮肤切换
浏览量追踪基于 Astro DB 实现的访问计数

1. 保存阅读进度

当用户在文章读到一半退出,下次再次访问时会弹出“要从上次的位置继续阅读吗?”提示的功能。

// ReadingPositionSave.astro (部分摘录)
const slug = window.location.pathname.split(").filter(Boolean).pop();
const storageKey = `reading-position-${slug}`;

// 保存滚动位置
window.addEventListener("scroll", () => {
 const percent = (scrollTop / docHeight) * 100;
 localStorage.setItem(storageKey, "String(percent));
});

核心点:

  • 使用 localStorage 实现位置持久化
  • 仅在 24 小时内且阅读进度超过 10% 时提示恢复
  • 5 秒后自动关闭 Toast 提示

2. 悬浮分享按钮

移动端在滚动时会显示在常用位置的悬浮按钮。

User
User

手机端分享按钮太难按了。

Bot
Bot

有了悬浮按钮,分享链接始终就在大拇指可以够到的地方!

支持平台:

  • X (Twitter)
  • LINE
  • 复制链接

3. 代码复制按钮

自动为所有的 <pre> 标签添加复制按钮。

// CopyCodeButton.astro
document.querySelectorAll("pre").forEach((block) => {
 const button = document.createElement("button");
 button.textContent = "Copy";
 button.addEventListener("click", async () => {
 await navigator.clipboard.writeText(block.textContent);
 button.textContent = "Copied!";
 });
 block.appendChild(button);
});

4. 键盘快捷键

面向高级用户的快捷操作功能。

快捷键动作
Cmd/Ctrl + K聚焦搜索框
Escape取消搜索聚焦
/聚焦搜索框

5. Toast 气泡通知系统

可以通过 window.showToast() 在任何地方触发通知。

// 使用示例
window.showToast({
 message: "已复制到剪贴板", type: "success", // success, error, info, warning
 duration: 3000,
});

总结

这些功能已经集成在 PostLayout.astro 中,并在所有文章页面自动启用。

所有组件列表
  • ReadingProgress.astro - FloatingShare.astro - CopyCodeButton.astro - KeyboardShortcuts.astro - Toast.astro - ReadingPositionSave.astro - ViewCounter.astro

下一篇我将详细讲解浏览量追踪功能的具体实现。