原理:点击按钮返回顶部效果(js):用了一个定时器,每30ms滚动条的位置上移一点,上移的距离越来越小,越靠近顶部上移的速度越慢,当滚动条距离顶部为0 ,删除定时器;或者在返回顶部的过程中用户移动滚动条,结束返回顶部效果,删除定时器,在当前页面停下来。
下面给个小demo,大家也可以自己试一试
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<style>
div.a{
width:300px;
height:10000px;
}
div.b{
width:100%;
height:950px;
position:relative;
background:yellow;
}
#btn{
position: fixed;
bottom:20px;
right:20px;
width:100px;
height:100px;
border:1px solid red;
display: none;
}
</style>
</head>
<body>
<div class='a'>
<div class='b'></div>
</div>
<div id="btn">返回顶部</div>
<script>
window.onload = function(){
var btn = document.getElementById('btn');
var timer = null;
var isTop = true;
//获取页面可视区高度
var clientHeight = document.documentElement.clientHeight;
console.log(clientHeight)
//滚动条滚动时触发
window.onscroll = function() {
//显示回到顶部按钮
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
if (osTop >= clientHeight) {
btn.style.display = "block";
} else {
btn.style.display = "none";
};
//回到顶部过程中用户滚动滚动条,停止定时器
if (!isTop) {
clearInterval(timer);
};
isTop = false;
};
btn.onclick = function() {
//设置定时器
timer = setInterval(function(){
//获取滚动条距离顶部高度
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
console.log('osTop '+osTop);
var ispeed = Math.floor(-osTop / 7);
console.log('ispeed '+ispeed);
document.documentElement.scrollTop = document.body.scrollTop = osTop+ispeed;
//到达顶部,清除定时器
if (osTop == 0) {
clearInterval(timer);
};
isTop = true;
},30);
};
};
</script>
</body>
网友评论