scrollTo speed/duration setting

后端 未结 2 402
耶瑟儿~
耶瑟儿~ 2020-12-17 10:33

Is there a way to speed up the behavior speed of scrollTo?

I had a stab in the dark at speed and duration but don\'t work!

2条回答
  •  春和景丽
    2020-12-17 10:48

    Working solution using Promise:

    function scrollDelay(ms) {
        return new Promise(res => setTimeout(res, ms));
    }
    
    document.getElementById("slow-scroll-demo-button").onclick = async function() {
        for (var y = 0; y <= 4200; y += 100) {
            window.scrollTo({top: y, behavior: 'smooth'})
            await scrollDelay(100)
        }
    }
    

    Trick to introduce delay in scrolling:

    1. Create an async function called scrollDelay() that spends time by calling a promise

    2. Call the scrollDelay along with scrollTo in a for loop

提交回复
热议问题