reactjs 页面平滑跳转



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
    }
}

}


使用的时候只要设定scrollTarget的值然后调用smoothScrollVertical即可


let height = document.getElementById("techIntroduction").offsetTop - 60
scrollTarget = height
smoothScrollVertical()


具体的效果请见:http://www.aqrose.com
阿丘科技官网使用该技术进行页面不同部分的平滑跳转

你可能感兴趣的:(reactjs 页面平滑跳转)