scrollSmoothToPosition

// 页面垂直平滑滚动到指定滚动高度
const scrollSmoothTo = (position) => {
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback, element) {
            return setTimeout(callback, 17);
        };
    }
    // 当前滚动高度
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    // 滚动step方法
    const step = () => {
        // 距离目标滚动距离
        let distance = position - scrollTop;
        // 目标滚动位置
        scrollTop = scrollTop + distance / 5;
        if (Math.abs(distance) < 1) {
            window.scrollTo(0, position);
        } else {
            window.scrollTo(0, scrollTop);
            requestAnimationFrame(step);
        }
    };
    step();
};

  

// IOS 兼容性不好
window.scrollTo({
    top: number,
    behavior: 'smooth',
});

  

posted @ 2023-01-30 16:35  671_MrSix  阅读(9)  评论(0编辑  收藏  举报