Jekyll添加返回顶部按钮

2021-09-01

有些时候,写的文章会很长,为了更方便回到顶部的地方,还得需要添加返回顶部的按钮,本文介绍一种添加返回顶部按钮的简单方法。

一、添加css和js

将font-awesome.min.css和jquery.min.js添加到head.html中

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css">
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>

二、添加返回按钮块

将以下代码添加到博文采用的布局html文件的最后,比如我的是footer.html中,网站全局均可使用。

<div id="backtop">
<a href="#"><i class="fa fa-arrow-up" aria-hidden="true"></i></a>
</div>

三、添加js代码

以下代码放在<body></body>的最下面

<script type="text/javascript">
$("#backtop").hide();
$(document).ready(function () {
  $(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
      $('#backtop').fadeIn();
    } else {
      $('#backtop').fadeOut();
    }
  });
  $('#backtop a').click(function () {
    $('body,html').animate({
      scrollTop: 0
    }, 500);
    return false;
  });
});
</script>

四、添加按钮的css样式

#backtop {
  position: fixed;
  bottom: 30px;
  right: 0%;
  margin-right: 40px;
  background-color: #aaa;
  -webkit-border-radius: 7px;
  -moz-border-radius: 7px;
  border-radius: 7px;
  -webkit-transition: 0.7s;
  -moz-transition: 0.7s;
  transition: 0.7s;
}

#backtop a {
  /* back to top button */
  text-align: center;
  line-height: 40px;
  font-size: 20px;
  width: 40px;
  height: 40px;
  position: fixed;
  bottom: 16px;
  /* 小按钮到浏览器底边的距离 */
  right: 20px;
  /* 小按钮到浏览器右边框的距离 */
  color: #495057;
  /* 小按钮中文字的颜色 */
  z-index: 1000;
  background: #ced4da;
  /* 小按钮底色 */
  padding: auto;
  /* 小按钮中文字到按钮边缘的距离 */
  border-radius: 50px;
  /* 小按钮圆角的弯曲程度(半径)*/
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  font-weight: normal;
  /* 小按钮中文字的粗细 */
  -webkit-text-stroke: 2px #ced4da;
  /* 让fontawesome图标字体变细 */
  text-decoration: none !important;
}

到此也就完成了返回顶部按钮的功能

参考文章:

http://liberize.github.io/tech/jekyll-add-back-to-top-button.html

https://blog.smslit.cn/2015/10/28/backToTop-Jekyll/