点击按钮之后可以由快到慢地回到顶部,处于顶部位置时按钮消失,按钮位于页面的右下方。
<!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>Document</title>
<style>
.top {
width: 100%;
height: 200px;
background-color: red;
}
body {
height: 2000px;
}
.item1 {
position: fixed;
display: block;
right: 40px;
bottom: 40px;
height: 40px;
width: 100px;
display: none;
}
.item2 {
position: fixed;
display: block;
right: 40px;
bottom: 40px;
height: 40px;
width: 100px;
}
</style>
</head>
<body>
<div class="top"></div>
<button id="btn" class="item1">返回</button>
<script>
var btn = document.getElementById("btn")
btn.addEventListener("click",handler)
function handler() {
var b = document.documentElement.scrollTop
var a = setInterval(
function () {
var b = document.documentElement.scrollTop
var c = Math.ceil(b / 10)
document.documentElement.scrollTop = b - c
if(b==0){
clearInterval(a)
}
}, 1)
}
window.onscroll = function () {
console.log(document.documentElement.scrollTop || document.body.scrollTop)
if ((document.documentElement.scrollTop || document.body.scrollTop) > 200) {
btn.className = "item2"
}else{
btn.className = "item1"
}
}
</script>
</body>
</html>
页面返回顶部