仅 CSS 阅读进度条

为了构建一个阅读进度条,即显示用户向下滚动时阅读文章的进度,很难不考虑 JavaScript。但是,事实证明,您也可以使用纯 CSS 构建阅读进度条。

从本质上讲,一个名为 animation-timeline 的新实验性 CSS 属性可以让你指定用于控制 CSS 动画进度的时间轴。我们将用它来创建阅读进度条。

首先,我们需要定义一个用作进度条的 div 元素。我们将使用一个固定在视口顶部的容器来包装这个 div 。这将确保用户向下滚动页面时进度条始终可见。

html 复制代码
<div class="progress-bar-container">
    <div class="progress-bar"></div>
</div>
<div class="content">
    <!-- content goes here -->
</div>

接下来,我们将定义进度条的样式。我们将设置 progress-bar-container 固定在视口顶部并调整其背景颜色,该颜色始终对用户可见。我们还将 progress-bar 设置为 100% 宽度。

css 复制代码
.progress-bar-container {
    position: fixed;
    top: 0px;
    width: 100%;
    background: #6c2fa2;
    z-index: 999;
}

现在,为了使进度条动画化,我们将为 progress-bar 使用不同的背景颜色,并将其高度设置为 7px 。我们还将 animation-name 设置为 width ,这实际上将进度条的宽度从 0 动画到 100%

最后,我们将 animation-timeline 设置为 scroll(y) ,将动画时间轴绑定到视口的垂直滚动位置。这将确保当用户向下滚动页面时进度条具有动画效果。

css 复制代码
.progress-bar {
    height: 7px;
    background: #e131ff;
    animation-name: width;

    /* animation timeline is tied to vertical scroll position */
    animation-timeline: scroll(y);
}

@keyframes width {
    from { width: 0 }
    to   { width: 100% }
}

就是这样!您可以在下面看到它的实际效果。

由于 animation-timeline 属性仍处于实验阶段,因此并非所有浏览器(准确地说是 FirefoxSafari)都支持它。

您可以检查浏览器的兼容性并据此使用。

相关推荐
哀木1 小时前
一个简单的套壳方案,就能让你的 Agent 少做重复初始化
前端
问心无愧05131 小时前
ctf show web入门27
前端
小村儿1 小时前
给 AI Agent 装上"长期记忆":Karpathy 的 LLM Wiki 思想,我做成了工具
前端·后端·ai编程
竹林8181 小时前
用ethers.js连接MetaMask实现Web3钱包登录:从踩坑到稳定运行的完整记录
前端·javascript
heyCHEEMS1 小时前
如何用 Recast 实现静态配置文件源码级读写
前端·node.js
心连欣1 小时前
从零开始,学习所有指令!
前端·javascript·vue.js
review445431 小时前
大模型和function calling分别是如何工作的
前端
东东同学1 小时前
耗时一个月,我把 Nuxt 首屏性能排障经验做成了一个 AI Skill
前端·agent
冴羽2 小时前
超越 Vibe Coding —— AI 辅助编程指南
前端·ai编程·vibecoding
梦想的颜色3 小时前
一天一个SKILL——前端最佳自动化测试 webapp-testing
前端·web app