smooth scroll to top

前端 未结 12 1222
眼角桃花
眼角桃花 2020-12-07 22:58

I\'ve bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors

12条回答
  •  盖世英雄少女心
    2020-12-07 23:36

    Came up with this solution:

    function scrollToTop() {
    let currentOffset = window.pageYOffset;
    const arr = [];
    
    for (let i = 100; i >= 0; i--) {
        arr.push(new Promise(res => {
                setTimeout(() => {
                        res(currentOffset * (i / 100));
                    },
                    2 * (100 - i))
            })
        );
    }
    
    arr.reduce((acc, curr, index, arr) => {
        return acc.then((res) => {
            if (typeof res === 'number')
                window.scrollTo(0, res)
            return curr
        })
    }, Promise.resolve(currentOffset)).then(() => {
        window.scrollTo(0, 0)
    })}
    

提交回复
热议问题