首页 > 解决方案 > 如何在纯 JavaScript 中添加平滑滚动动画?

问题描述

我正在使用纯 JavaScript 进行垂直滚动。我需要这个滚动才能有流畅的行为。

function move_up(scroll_nav)
    {
        var container = document.getElementById(scroll_nav);
        upScroll(container,'up',40,50,10);

    }

    function move_down(scroll_nav)
    {
        var container = document.getElementById(scroll_nav);
        upScroll(container,'down',40,50,10);

    }

    function upScroll(element,direction,speed,distance,step)
    {
        scrollAmount = 0;
        var slideTimer = setInterval(function(){
            if(direction == 'up'){
                element.scrollTop  -= step;
            } else {
                element.scrollTop  += step;
            }
            scrollAmount += step;
            if(scrollAmount >= distance){
                window.clearInterval(slideTimer);
            }
        }, speed);
    }

我需要一个类似于此链接中的动画函数,但没有 jquery。 https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_smooth_scroll_jquery

我需要一个动画功能,请提供解决方案。

标签: javascripthtmlcssscroll

解决方案


element.scrollTo({ top: ..., behavior: 'smooth' });


推荐阅读