在 jQuery 中你可以做类似的事情
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 1000);
我感兴趣的是如何仅在 Javascript 中处理这个问题?
谢谢!
最佳答案
这个问题通常通过利用 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'
)。
关于javascript - javascript 中的平滑滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26625387/