js实现回到顶部

当鼠标从顶部滚动超过一定距离后,显示返回顶部按钮,点击按钮,页面平滑滚动到顶部,按钮隐藏。

CSS

1
2
3
4
5
6
7
8
9
10
position: fixed;
bottom: 20px;
right: 20px;
background-color: rgb(216, 72, 72);
width: 50px;
height: 50px;
line-height: 50px;
text-align: center;
border-radius: 50%;
cursor: pointer;

几种js实现方式

1
2
3
4
5
6
7
8
// (1)
document.scrollingElement.scrollTop = 0;

// (2)
// 此种写法第一个参数是left的距离,第二个参数是top的距离
window.scrollTo(0, 0)
// top也可以换成left,另外第二个参数behavior表示滚动的方式,默认为auto,经测试与值为instant时相同,都是立刻滚动到指定位置,而smooth则是平滑的滚动。
window.scrollTo({top: 0, behavior: "smooth"})

完美的获取scrollTop的方式

1
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;