Hugo:阅读进度条

Posted by Nefelibata on Tue 2024-04-02 | | about 1 mins
Last Modified on Thu 2024-05-23

1 显示效果

今天突然想起来可以搞一个阅读进度条的功能,还挺好看的,通过一番搜寻找到了一个很不错的解决方案,最终实现效果如下:

image-20240402205117047

2 解决方案

要实现在所有页面上可以实现这个效果,可以将html代码插入到 layouts\_default\baseof.html 并引用css和js文件,若是只想在文章页面实现,可以插入到 layouts\_default\single.html

2.1 html

1<progress id="content_progress" value="0"></progress>
2<link rel="stylesheet" href="/css/progress.css">
3<script src="/js/progress.js"></script>

2.2 css

 1#content_progress {
 2    /* Positioning */
 3    position: fixed;
 4    left: 0;
 5    top: 0;
 6    z-index: 1000;
 7    width: 100%;
 8    height: 3px;
 9    -webkit-appearance: none;
10    -moz-appearance: none;
11    appearance: none;
12    border: none;
13    background-color: transparent;
14    color: #0085a1;
15}
16
17#content_progress::-webkit-progress-bar {
18    background-color: transparent;
19}
20
21#content_progress::-webkit-progress-value {
22    background-color: #0085a1;
23}
24
25#content_progress::-moz-progress-bar {
26    background-color: #0085a1;
27}

2.3 JavaScript

 1document.addEventListener('DOMContentLoaded', function () {
 2      var winHeight = window.innerHeight,
 3            docHeight = document.documentElement.scrollHeight,
 4            progressBar = document.querySelector('#content_progress');
 5      progressBar.max = docHeight - winHeight;
 6      progressBar.value = window.scrollY;
 7
 8      document.addEventListener('scroll', function () {
 9            progressBar.max = document.documentElement.scrollHeight - window.innerHeight;
10            progressBar.value = window.scrollY;
11      });
12});

参考资料: