以下是如何完成一个滚动进度栏,随着您滚动网站的页面,它是传递进度指标的好方法,让读者知道他们在帖子中有多远。
它使用了 CSS 变量的力量,该解决方案是由 Lea Verou 的一部分改编的(https://www.youtube.com/watch?v=2an6-WVPuJU)。
首先,在打开体标签后直接添加以下标记:
1<div class="progress"></div>
然后用这样的东西来设计这个.progress 元素:
1.progress {
2 background: linear-gradient(to right, #F9EC31 var(--scroll), transparent 0);
3 background-repeat: no-repeat;
4 position: fixed;
5 width: 100%;
6 height: 4px;
7 z-index: 1;
8}
注意在 线性梯度中,我们是指一个名为 --scroll
的 CSS 变量,在滚动时会给出一个值。
这意味着剩下的只是听取文档的滚动事件,并用滚动百分比设置--scroll
自定义属性的值。
感谢 Phil Ricketts和他对这个 StackOverflow 问题的解决方案,以准确的方式来计算文档滚动百分比:
1var h = document.documentElement,
2 b = document.body,
3 st = 'scrollTop',
4 sh = 'scrollHeight',
5 progress = document.querySelector('.progress'),
6 scroll;
7
8document.addEventListener('scroll', function() {
9 scroll = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
10 progress.style.setProperty('--scroll', scroll + '%');
11});
👉 请注意,IE或Edge目前不支持CSS自定义属性,但支持正在到来,同时该功能会优雅地降低。