<pre>
<code>
const scrollTarget = 0
const smoothScrollVertical = () => {
let startScroll = null
let currentTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
const step = 7
let scrollBottom = document.body.scrollHeight - currentTop - document.documentElement.clientHeight
console.log(currentTop,scrollBottom)
if(Math.abs(currentTop - scrollTarget) <= 1.1){
cancelAnimationFrame(startScroll)
console.log("finish")
return
}
if(currentTop > scrollTarget){
// current positon is below target, up
startScroll = window.requestAnimationFrame(smoothScrollVertical)
window.scrollTo(0, currentTop + Math.min((scrollTarget - currentTop)/step, -1))
if(currentTop == 0){
cancelAnimationFrame(startScroll)
console.log("finish")
return
}
}
else if(currentTop < scrollTarget){
// current positon is up to target down
startScroll = window.requestAnimationFrame(smoothScrollVertical)
window.scrollTo(0, currentTop + Math.max((scrollTarget - currentTop)/step, 1))
if(scrollBottom <= 1.1){
cancelAnimationFrame(startScroll)
console.log("finish")
return
}
}
}
</code>
</pre>
使用的时候只要设定scrollTarget的值然后调用smoothScrollVertical即可
<pre>
<code>
let height = document.getElementById("techIntroduction").offsetTop - 60
scrollTarget = height
smoothScrollVertical()
</code>
</pre>
具体的效果请见:http://www.aqrose.com
阿丘科技官网使用该技术进行页面不同部分的平滑跳转