一、需求
点击按钮之后可以由快到慢地回到顶部,处于顶部位置时按钮消失
二、实现原理
需求 | 实现原理 | |||
---|---|---|---|---|
|
| |||
| 给全局设置scroll-behavior:smooth实现平稳的滚动 | |||
使用animate()方法,自定义滚轮条位置和动画速度 | ||||
|
|
三、代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BACK</title>
<style>
*{
margin: 0;
padding: 0;
}
.container{
height: 3000px;
width: 100%;
scroll-behavior: smooth;/*设置滚动条平滑*/
}
.back{
position: fixed;
right: 10px;
bottom: 10px;
height: 50px;
width: 50px;
content: 'back';
border-radius: 20%;
background-color: #364c7b;
font-weight: bold;
text-align: center;
font-size: 18px;
color: #b0b0b0;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<div class="back" id="back">返回顶部</div>
</div>
<script src="./js/jqurey-3.6.3.js"></script>
<script>
const back = document.getElementById('back')
//声明获取返回顶部提示
back.onclick = function(){
$('html').animate({scrollTop:0},600) //设置滚动条停止位置,和滚动速度,数值越大速度越慢
}
//设置提示顶部消失
$(window).scroll(function(){
if($(this).scrollTop()>100){ //大于100像素时显示提示
$(".back").show()
}else{
$(".back").hide() //反之隐藏
}
})
</script>
</body>
</html>