Smooth JavaScript/jQuery scroll to element

前端 未结 2 376
难免孤独
难免孤独 2021-01-14 23:44

I\'m trying to make a horizontal scroll website, but I don\'t know how to smoothly scroll from one element to the other. I tried the following code:



        
相关标签:
2条回答
  • 2021-01-14 23:49

    untested

       $('.click').click(function(){
            $.scrollTo( $('.last'), 800);
        });
    
    0 讨论(0)
  • 2021-01-14 23:52

    In case you have to / need to avoid using jQuery here is vanilla JS solution which worked for us nicely:

    function scrollToElement(myElement, scrollDuration = 500) {
        const elementExists = document.querySelector(myElement);
        if (elementExists && elementExists.getBoundingClientRect) {
            const rect = elementExists.getBoundingClientRect();
            const elementTop = rect.top + window.scrollY - 200; // a bit of space from top
            var cosParameter = (window.scrollY - elementTop) / 2,
                scrollCount = 0,
                oldTimestamp = performance.now();
            function step(newTimestamp) {
                console.log(scrollCount);
                scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
                if (scrollCount >= Math.PI) {
                    window.scrollTo(0, elementTop);
                    return;
                }
                window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount)) + elementTop);
                oldTimestamp = newTimestamp;
                window.requestAnimationFrame(step);
            }
            window.requestAnimationFrame(step);
        }
    }
    scrollToElement("#yourElement");

    I hope it helps :)

    0 讨论(0)
提交回复
热议问题