繁体   English   中英

滚动Java动画,Vanilla JS

[英]Javascript Animation on scroll, Vanilla JS

我想使用我在github上看到的这段代码,但是我不知道如何在HTML上应用此代码以产生滚动效果。

关键是,我不知道如何运行使用此代码

来源https://gist.github.com/andjosh/6764939

document.getElementsByTagName('button')[0].onclick = function () {
    scrollTo(document.body, 0, 1250); 
}

function scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){        
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
}

//t = current time
//b = start value
//c = change in value
//d = duration
Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
};

首先,您必须将document.body替换为document.documentElement因为不建议使用document.body.scrollTop()

编辑:似乎我不完全赞成弃用document.body.scrollTop()。 支持多种浏览器的最佳解决方案是检查两种情况。

其次,正如Quantastical已经指出的那样,您需要为“ to”参数设置一个大于0的值。

还要确保您有一个<button>元素。 那应该可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM