我正在寻找一个简单的,跨浏览器“滚动到顶部”的动画,我可以应用到一个链接。我不想需要一个JS库,如jQuery/Moo等。

// jQuery Equivilant to convert to pure JS...
$('html, body').animate({scrollTop:0}, 400);

对于那些在跳进图书馆之前应该100%学习JS的人来说,我是一个完美的例子。:(


当前回答

一件容易的事。

var scrollIt = function(time) {
    // time = scroll time in ms
    var start = new Date().getTime(),
        scroll = document.documentElement.scrollTop + document.body.scrollTop,
        timer = setInterval(function() {
            var now = Math.min(time,(new Date().getTime())-start)/time;
            document.documentElement.scrollTop
                = document.body.scrollTop = (1-time)/start*scroll;
            if( now == 1) clearTimeout(timer);
        },25);
}

其他回答

基于这里的一些答案,但使用了一些简单的数学,使用正弦曲线进行平稳过渡:

scrollTo(element, from, to, duration, currentTime) {
       if (from <= 0) { from = 0;}
       if (to <= 0) { to = 0;}
       if (currentTime>=duration) return;
       let delta = to-from;
       let progress = currentTime / duration * Math.PI / 2;
       let position = delta * (Math.sin(progress));
       setTimeout(() => {
           element.scrollTop = from + position;
           this.scrollTo(element, from, to, duration, currentTime + 10);
       }, 10);
   }

用法:

// Smoothly scroll from current position to new position in 1/2 second.
scrollTo(element, element.scrollTop, element.scrollTop + 400, 500, 0);

注:注意ES6风格

实际上有一个纯javascript的方式来完成这个不使用setTimeout或requestAnimationFrame或jQuery。

简而言之,在scrollView中找到要滚动到的元素,并使用scrollIntoView

el.scrollIntoView({行为:“平滑”});

这是一个普朗克。

线性滚动动画到底部。纯JS,没有JQuery。也许我的解决方案会对某人有所帮助。

let action_count = 8;
let speed_ms = 15;
let objDiv = document.getElementsByClassName('js_y5_area3').item(0);

let scroll_height = objDiv.scrollHeight;
let window_height = objDiv.offsetHeight;

let scroll_top = objDiv.scrollTop;
let need_scroll_top = scroll_height - window_height;

if (scroll_top < need_scroll_top)
{
    let step = Math.ceil((need_scroll_top - scroll_top) / action_count);

    let scrollInterval = setInterval(function()
    {
        scroll_top += step;
        objDiv.scrollTop = scroll_top;

        if (scroll_top >= need_scroll_top)
        {
            clearInterval(scrollInterval);
        }

    }, speed_ms);
}

你可以改变变量action_count, speed_ms来配置滚动动画。

没有人提到CSS属性滚动行为

CSS

html {
  scroll-behavior: smooth;
}

JS

window.scrollTo(0,0)

改编自下面的回答:

function scroll(y, duration) {

    var initialY = document.documentElement.scrollTop || document.body.scrollTop;
    var baseY = (initialY + y) * 0.5;
    var difference = initialY - baseY;
    var startTime = performance.now();

    function step() {
        var normalizedTime = (performance.now() - startTime) / duration;
        if (normalizedTime > 1) normalizedTime = 1;

        window.scrollTo(0, baseY + difference * Math.cos(normalizedTime * Math.PI));
        if (normalizedTime < 1) window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

这应该允许你平滑地滚动(余弦函数)从任何地方到指定的“y”。