通过定位中的fixed使按钮固定
然后通过js的滚动事件实现按钮到达顶部消失
最后通过js的计时器和点击事件实现由快到慢的返回顶部效果
<!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>页面返回顶部</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
width: 100%;
height: 3000px;
background-color: aqua;
position: relative;
text-align: center;
}
.clear{
width: 100px;
height: 100px;
position: fixed;
right: 0px;
top: 816px;
display: none;
}
</style>
</head>
<body>
<h2>顶部</h2>
<button id="btn" class="clear">
返回顶部
</button>
<script>
//绑定按钮
var obtn=document.querySelector("#btn")
//通过屏幕滚动事件来实现按钮block和none的赋值,进而实现到达屏幕顶端按钮消失的效果
window.onscroll = function() {
obtn.style.display="block"//开始赋予block
var height = document.documentElement.scrollTop||document.body.scrollTop
console.log(height)
//当height为0时,给按钮赋予none值
if(height==0){
obtn.style.display="none"
}
}
//通过计时器和点击事件来实现height(可视窗口与页面顶端的距离)的缓慢减小,进而实现屏幕从上到下由快到满的效果
obtn.addEventListener('click',handler)//赋予按钮点击事件
function handler(){
var height=document.documentElement.scrollTop
//计时器的使用
var retop=setInterval(
function(){
var height=document.documentElement.scrollTop
var speed=Math.ceil(height/50);//设置上升速度,通过height减去speed(随着hieght的减小而减小)让可视窗口与页面顶部的距离缓慢减小
document.documentElement.scrollTop=height-speed;
if(height==0){
clearInterval(retop)//特别注意这里的参数,不然会无法清除计时器。
}
},1)
}
</script>
</body>
</html>
页面返回顶部 -