<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>锚点定位</title>
<style>
* {
margin: 0;
padding: 0;
}
.tops {
position: fixed;
top: 0;
left: 0;
width: 100%;
line-height: 40px;
height: 40px;
}
.top {
margin: 10px;
cursor: pointer;
display: inline-block;
}
.top1 {
color: #b94a48;
}
.top2 {
color: #fb8c00;
}
.top3 {
color: #669900;
}
.top4 {
color: #c0a16b;
}
.boxs {
margin-top: 50px;
height: 500px;
overflow-y: auto;
}
.box {
margin: 0 auto;
width: 100%;
height: 1000px;
}
.box1 {
background: #b94a48;
}
.box2 {
background: #fb8c00;
}
.box3 {
background: #669900;
}
.box4 {
background: #c0a16b;
}
</style>
<script>
window.requestAnimationFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 6000 / 60)
}
})()
window.cancelAnimFrame = (function () {
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function (callback) {
window.clearTimeout(callback)
}
})()
function goPosition(index) {
let distance = document.getElementById(index).offsetTop - 50
const scrollTop1 = document.querySelector('.boxs').scrollTop
const direction = scrollTop1 > distance
const fn = () => {
let step = 0
const scrollTop = document.querySelector('.boxs').scrollTop
if (direction) { // 从下往上滑动
step = scrollTop - parseInt((scrollTop - distance) / 3)
const diff = scrollTop - distance
if (diff < 100 && diff > 0) {
step = scrollTop - 1
}
} else { // 从上往下滑动
step = distance - parseInt((distance - scrollTop) / 3)
const diff = distance - scrollTop
if (diff < 100 && diff > 0) {
step = scrollTop + 1
}
}
if (distance !== scrollTop) {
document.querySelector('.boxs').scrollTop = step
fn.rafTimer = window.requestAnimationFrame(fn)
} else {
window.cancelAnimationFrame(fn.rafTimer)
}
}
fn.rafTimer = window.requestAnimationFrame(fn)
}
</script>
</head>
<body>
<div class="tops">
<div class="top top1" onclick="goPosition('box1')">跳到第一个</div>
<div class="top top2" onclick="goPosition('box2')">跳到第二个</div>
<div class="top top3" onclick="goPosition('box3')">跳到第三个</div>
<div class="top top4" onclick="goPosition('box4')">跳到第四个</div>
</div>
<div class="boxs">
<div id="box1" class="box box1"></div>
<div id="box2" class="box box2"></div>
<div id="box3" class="box box3"></div>
<div id="box4" class="box box4"></div>
</div>
</body>
</html>
requestAnimationFrame实现由快到慢的锚点定位滚动
最新推荐文章于 2024-06-21 08:42:30 发布