需求
点击按钮之后可以由快到慢地回到顶部,处于顶部位置时按钮消失,按钮位于页面的右下方
原理
二次函数会有缓陡坡,设置为函数执行即可实现快慢、慢快效果
代码
<!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">
<style>
#btn {
display: none;
position: fixed;
bottom: 0;
right: 0;
background-color: black;
color: white;
}
</style>
<title>Document</title>
</head>
<body>
<button onclick="topFunction()" id="btn">返回顶部</button>
<div style="background-color:blue;color:white;">向下滑动</div>
<div style="background-color:gray;padding:30px 30px 2500px">网页返回顶部案例</div>
<script>
window.onscroll = function() {scrollFunction()};
//获取页面滚动值,如果大于0则设置btn显示,反之则不显示
function scrollFunction(){
if(document.documentElement.scrollTop>0){
document.getElementById("btn").style.display="block"
}
else
{
document.getElementById("btn").style.display="none"
}
}
//点击按钮,返回顶部
btn.onclick = function(){
var times = setInterval(function(){
var stop = window.scrollY;
var offset = stop - (stop*0.1+10);
if(offset>0){
window.scrollTo(0,offset)
}
else
{
window.scrollTo(0,0);
clearInterval(time)
}
},30)
}
</script>
</body>
</html>
效果