主要使用的是bom(浏览器对象模型)对象document.documentElement.scrollTop实现的。window.scrollY是只可读的,document.documentElement.scrollTop是可读可写的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
margin: 0;
padding: 0;
height: 5000px;
background-image: linear-gradient(to bottom,pink,yellow);
}
#totop{
position: fixed;
right: 0;
width: 35px;
height: 80px;
}
</style>
</head>
<body>
<button type="button" id="totop">回到顶部</button>
<script>
var otop=document.getElementById('totop');
var timer;
otop.onclick=function(){
clearInterval(timer);
timer=setInterval(function(){
document.documentElement.scrollTop-=500;
if(document.documentElement.scrollTop<=0){
clearInterval(timer);
}
},20);
}
</script>
</body>
</html>