function fnScrollToTop(toTopBtnId) {
var obtn = document.getElementById(toTopBtnId);
var clientHeight = document.documentElement.clientHeight;
var timer = null;
var isTop = true;
window.onscroll = function() {
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
if (osTop >= clientHeight) {
obtn.style.display = 'block';
} else {
obtn.style.display = 'none';
}
if (!isTop) {
clearInterval(timer);
}
isTop = false;
}
obtn.onclick = function() {
timer = setInterval(function() {
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var speed = Math.floor(-osTop / 6);
document.documentElement.scrollTop = document.body.scrollTop = osTop + speed;
isTop = true;
if (osTop == 0) {
clearInterval(timer);
}
}, 30);
}
}
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#btnTop{
display: none;position: fixed;right: 20px;bottom: 200px;
width: 48px;height: 48px;line-height: 48px;text-align: center;border-radius: 24px;
background: red;color: white;
}
</style>
</head><body>
<div style="height: 4000px;background: pink;">
1111111
</div>
<div>
2222222
</div>
<div id="btnTop">Top</div>
<script>
fnScrollToTop('btnTop');
</script>
</body></html>