其他分享
首页 > 其他分享> > 点击滚动到任意位置

点击滚动到任意位置

作者:互联网

涉及知识点:

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

 

标签:Dvalue,滚动,sensitivity,window,ScrollDown,点击,num,const,任意
来源: https://www.cnblogs.com/MrZhujl/p/11612423.html