在javascript中平滑滚动?

时间:2014-10-29 08:06:52

标签: javascript animation scroll

在jQuery中,您可以执行

之类的操作
$('html, body').stop().animate({
    'scrollTop': $target.offset().top
}, 1000);

我对如何在Javascript中处理此问题感兴趣?

谢谢!

1 个答案:

答案 0 :(得分:2)

此问题通常通过使用setInterval / setTimeout的函数回答,并以微小的增量滚动元素,请参阅:Cross browser JavaScript (not jQuery...) scroll to top animation

我想提出另一种更现代的方法,使用动态添加的CSS过渡,这应该更顺畅,更少耗费CPU。它使用CSS为body设置动画,JavaScript仅计算并设置元素的translateY()转换。 CSS动画完成后,将删除变换并设置滚动位置。

演示:http://jsfiddle.net/00uw1Lq9/4/(跨浏览器修复后的更新链接)。

仅适用于具有无前缀转换和转换的浏览器(在IE11,当前Chrome和Firefox中测试),对于旧版本,您可能需要添加前缀检测。它也可能在某些方面被打破,把它当作一个起点而不是一个解决方案。

// this function self-initializes and attaches an event listener to the root element
var smoothScroll = (function(root){
     //keep track of the target element between scrolling function and transitionend callback
     var targetElement;
    // called when the CSS transition finishes
    root.addEventListener('transitionend', function(e){
        // remove transition and transform
        root.style['transition'] = '';
        root.style['transform'] = '';
        // do the actual scrolling
        targetElement.scrollIntoView();
    });
    // this function fill be available as the smoothScroll function
    return function(element, time){
        // get the top position of target element
        var offset = element.offsetTop - root.scrollTop;
        // if the element is very low it can't get scrolled up to the top of the window
        offset = Math.min( offset, root.offsetHeight - document.documentElement.clientHeight );
        // save reference to the target element for callback
        targetElement = element;
        // set transfor/transition CSS properties
        root.style['transition'] = 'transform';
        root.style['transition-duration'] = time;
        // this fakes the scrolling animation by animating transform on the element
        root.style['transform'] = 'translateY(' + offset * -1 +'px)';
    }
}(document.body));

用法:smothScroll( DOMNodeReference, time ),其中time是对CSS transition-duration属性有效的字符串(例如'300ms''2.5s')。