HTML:
<a id="gototop" class="gotop" title="回到顶部"></a>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
// 滚动显示/隐藏
$(window).scroll(function(){
if($(window).scrollTop() > 200){
$(".gotop").fadeIn(300);
}else{
$(".gotop").fadeOut(300);
}
});
// 平滑返回顶部
$(".gotop").click(function(){
$("html,body").animate({
scrollTop: 0
}, 600); // 600 毫秒 = 非常平滑
return false;
});
});
</script>
可以调整的平滑参数,想更快 / 更慢?只改上文这里:
animate({scrollTop:0}, 600);
300:快
600:标准平滑(推荐)
800:很慢很柔
CSS:
.gotop {
width:47px;
height:47px;
position:fixed;
right:10px;
bottom:10px;
display:none;
background:url(../images/gototop.png) no-repeat left top;
cursor: pointer; /* 加个手型,体验更好 */
}
.gotop:hover {
background:url(../images/gototop.png) no-repeat 0 -46px;
}
图标文件:

