2014-10-29 85 views
2

在jQuery中,你可以做这样的事情在JavaScript中平滑滚动?

$('html, body').stop().animate({ 
    'scrollTop': $target.offset().top 
}, 1000); 

而且我很感兴趣如何在只有JavaScript处理呢?

谢谢!

回答

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')的字符串。

+0

非常有趣!你有没有在任何地方做过改进或其他的例子? – 2015-03-06 23:35:07