Hugo:一键回到顶部

Posted by Nefelibata on Wed 2024-03-27 | | about 1 mins
Last Modified on Thu 2024-05-23

文章参考自:https://github.com/sengmitnick/hugo-theme-hello-friend-ng/commit/9e6ba0cc1940ffa200fdf21787e7e808d2f126d0

显示效果

image-20240327172004055

右下角显示回到顶部按钮

解决方案

添加代码: layouts/partials/backtop.html

代码如下:

 1<style>
 2    /* add BackTop */
 3    #backtop {
 4        color: #c2c0c0;
 5        position: fixed;
 6        right: 25px;
 7        bottom: 25px;
 8        width: 35px;
 9        height: 35px;
10        z-index: 999998;
11
12        /* cursor: pointer; */
13    }
14</style>
15<div id="backtop">
16    <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="chevron-circle-up" class="svg-inline--fa fa-chevron-circle-up fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
17        <path fill="currentColor" d="M8 256C8 119 119 8 256 8s248 111 248 248-111 248-248 248S8 393 8 256zm231-113.9L103.5 277.6c-9.4 9.4-9.4 24.6 0 33.9l17 17c9.4 9.4 24.6 9.4 33.9 0L256 226.9l101.6 101.6c9.4 9.4 24.6 9.4 33.9 0l17-17c9.4-9.4 9.4-24.6 0-33.9L273 142.1c-9.4-9.4-24.6-9.4-34 0z">
18        </path>
19    </svg>
20    
21</div>
22<script>
23    var timer = null;
24    backtop.onclick = function () {
25        cancelAnimationFrame(timer);
26        //获取当前毫秒数
27        var startTime = +new Date();
28        //获取当前页面的滚动高度
29        var b = document.body.scrollTop || document.documentElement.scrollTop;
30        var d = 500;
31        var c = b;
32        timer = requestAnimationFrame(function func() {
33            var t = d - Math.max(0, startTime - (+new Date()) + d);
34            document.documentElement.scrollTop = document.body.scrollTop = t * (-c) / d + b;
35            timer = requestAnimationFrame(func);
36            if (t == d) {
37                cancelAnimationFrame(timer);
38            }
39        });
40    }
41
42</script>

然后在 layouts/_default/baseof.html 里面添加

1{{ partial "backtop.html" . }}