实现效果可以见我的个人博客(手机端返回顶部按钮不可见), 往下滚动一定距离就可在右下角看见
这个小功能(主要是不想直接用锚点跳转,但是后来发现 PC 端其实 Home 键更香)折腾了我这个小白一上午
环境说明
layout模板:Pug(Jade)
css预处理:Less (就直接用css也可)
注意:过低版本的浏览器可能不支持此法
功能实现
- 只有当页面向下滚动一定距离后,返回顶部按钮才出现
- 返回顶部按钮用纯css实现,不需要添加图片
- 平滑的返回顶部效果
代码
Pug部分
先在 /themes/layout/_partial
目录中创建文件 totop.pug
//- totop.pug
div#totop(title="返回顶部")
script(type='text/javascript', src= '/js/totop.js', async)
然后在需要添加返回顶部按钮的pug布局文件合适位置(一般为 block main
的尾部)中添加代码
include _partial/totop
css部分
在主题配置的less(或css)文件中添加如下代码,其中的距离使用的是固定距离,right 和 bottom 的值可自己调整
#totop{
position: fixed;
right: 35px;
bottom: 35px;
width: 0;
height: 0;
border-width: 0 7px 7px;
border-style: solid;
/* 下面的#a52a2a可以替换为你喜欢的颜色 */
border-color: transparent transparent #a52a2a;
display: none;
}
js部分
在主题的 source/js/
目录下添加 totop.js
文件
/* totop.js */
function backToTop(){
document.documentElement.scrollIntoView({
behavior: "smooth"
});
}
window.onscroll = function(){
var scrollTop = this.document.documentElement.scrollTop || this.document.body.scrollTop;
var totopBtn = this.document.getElementById("totop");
if(scrollTop < 200){
totopBtn.style.display="none";
}
else{
totopBtn.style.display="inline";
totopBtn.addEventListener('click',this.backToTop,false);
}
}