Smooth scroll to specific div on click

后端 未结 7 1434
抹茶落季
抹茶落季 2020-11-28 02:36

What I\'m trying to do is make it so that if you click on a button, it scrolls down (smoothly) to a specific div on the page.

What I need is if you click on the butt

相关标签:
7条回答
  • 2020-11-28 03:06

    I played around with nico's answer a little and it felt jumpy. Did a bit of investigation and found window.requestAnimationFrame which is a function that is called on each repaint cycle. This allows for a more clean-looking animation. Still trying to hone in on good default values for step size but for my example things look pretty good using this implementation.

    var smoothScroll = function(elementId) {
        var MIN_PIXELS_PER_STEP = 16;
        var MAX_SCROLL_STEPS = 30;
        var target = document.getElementById(elementId);
        var scrollContainer = target;
        do {
            scrollContainer = scrollContainer.parentNode;
            if (!scrollContainer) return;
            scrollContainer.scrollTop += 1;
        } while (scrollContainer.scrollTop == 0);
    
        var targetY = 0;
        do {
            if (target == scrollContainer) break;
            targetY += target.offsetTop;
        } while (target = target.offsetParent);
    
        var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
                                     (targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
    
        var stepFunc = function() {
            scrollContainer.scrollTop =
                Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);
    
            if (scrollContainer.scrollTop >= targetY) {
                return;
            }
    
            window.requestAnimationFrame(stepFunc);
        };
    
        window.requestAnimationFrame(stepFunc);
    }
    
    0 讨论(0)
提交回复
热议问题