这里作者用三种方式实现实现回到顶部功能都涉及到原生JS的scrollTop,scrollTo、scrollBy。
接下来我们就进入我们今天的正题:
我们先把css 和 DOM结构 给搭建好;
<body style="height: 1500px;">
<div id="box" class="box">
<div class="box-in"></div>
</div>
</body>
<style>
.box {
position: fixed;
right: 10px;
bottom: 10px;
height: 30px;
width: 50px;
text-align: center;
padding-top: 20px;
background-color: lightblue;
border-radius: 20%;
overflow: hidden;
}
.box::before {
position: absolute;
top: -50%;
left: 50%;
transform: translate(-50%, -50%);
content: "回到顶部";
width: 40px;
color: peru;
font-weight: bold;
}
.box:hover:before {
top: 50%;
}
.box:hover .box-in {
visibility: hidden;
}
.box-in {
display: inline-block;
height: 20px;
width: 20px;
border: 3px solid black;
border-color: white transparent transparent white;
visibility: visible;
transform: rotate(45deg);
}
第①种: scrollTop
<script>
var box = document.getElementById("box"),
timer = null;
box.onclick = function () {
cancelAnimationFrame(timer);
timer = requestAnimationFrame(function fn() {
var oTop = document.body.scrollTop || document.documentElement.scrollTop;
if (oTop > 0) {
document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
timer = requestAnimationFrame(fn);
} else {
cancelAnimationFrame(timer);
}
});
}
</script>
第②种:scrollTo
<script>
var box = document.getElementById("box"),
timer = null;
box.onclick = function () {
cancelAnimationFrame(timer);
timer = requestAnimationFrame(function fn() {
var oTop = document.body.scrollTop || document.documentElement.scrollTop;
if (oTop > 0) {
scrollTo(0, oTop - 350);
timer = requestAnimationFrame(fn);
} else {
cancelAnimationFrame(timer);
}
});
}
</script>
第三种:scrollBy,这种是手动挡的;
<script>
var box = document.getElementById("box"),
timer = null;
box.onclick = function () {
cancelAnimationFrame(timer);
timer = requestAnimationFrame(function fn() {
var oTop = document.body.scrollTop || document.documentElement.scrollTop;
if (oTop > 0) {
scrollBy(0, -50);
timer = requestAnimationFrame(fn);
} else {
cancelAnimationFrame(timer);
}
});
}
</script>
还有一种方式是通过 setInterval()的方式实现回到顶部的效果,那种方式挺简单的,今天我们的重点是讲AnimationFrame的方式实现回到顶部的效果。