html:
<!-- 置顶 -->
<div class="to_top_btn"></div>
css:
/* 置顶图标 */
.to_top_btn {
width: 0.79rem;
height: 0.79rem;
background: url("https://res.tuoluohuodong.com/1574923960.png")no-repeat center center;
background-size: 100% 100%;
bottom: 2.02rem;
right: 0.3rem;
z-index: 999;
cursor: pointer;
position: fixed;
}
js:
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
//初始化置顶按钮位置
$('.to_top_btn').css('right',($(window).width()-$('.container').width())/2-$('.to_top_btn').width()+"px");
//置顶按钮
$(window).scroll(function(){if($(document).scrollTop()>160){
$('.to_top_btn').fadeIn();
}else{
$('.to_top_btn').fadeOut();
}});
$('.to_top_btn').click(function(){
var timer=setInterval(function(){
if($(document).scrollTop()==0){
clearInterval(timer);
}else{
$(document).scrollTop($(document).scrollTop()-30);
}
},5);
});
</script>