<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>
使用的時(shí)候只要設(shè)定scrollTarget的值然后調(diào)用smoothScrollVertical即可
<pre>
<code>
let height = document.getElementById("techIntroduction").offsetTop - 60
scrollTarget = height
smoothScrollVertical()
</code>
</pre>
具體的效果請(qǐng)見:http://www.aqrose.com
阿丘科技官網(wǎng)使用該技術(shù)進(jìn)行頁(yè)面不同部分的平滑跳轉(zhuǎn)