点击滚动到任意位置

涉及知识点:

window.scrollTo(x, y)
requestAnimationFrame(()=>{})  //帧动画,优点:按浏览器的刷新频率渲染,更加流畅。特点:类似 setTimeout 只执行一次

啥也不说上代码:

  num 是需要到达的位置, 数字类型。调用:this.transitionScroll(100)

transitionScroll = (num) => {
    const n = window.pageYOffset;
    if(num < n) {
        this.ScrollDown(num)
    }
    if(num > n) {
        this.ScrollUp(num)
    }
}

ScrollDown = (num) => {
    const sensitivity = 5; //灵敏度
    window.requestAnimationFrame(() => {
        const n = window.pageYOffset;
        const Dvalue = Math.abs(num - n);
        if (num > n + sensitivity) {
            window.scrollTo(0, n + parseInt(Dvalue / sensitivity))
            this.ScrollDown(num)
        }
    })
}
   
ScrollDown = (num) => {
    const sensitivity = 5;
    window.requestAnimationFrame(() => {
        const n = window.pageYOffset;
        const Dvalue = Math.abs(num - n);
        if (num < n - sensitivity) {
            window.scrollTo(0, n - parseInt(Dvalue / sensitivity))
            this.ScrollDown(num)
        }
    })
}

 

你可能感兴趣的:(点击滚动到任意位置)