我试图制作一部动画片"滚动到顶部"不使用jQuery的效果。
在jQuery中,我通常使用这段代码:
$('#go-to-top').click(function(){
$('html,body').animate({ scrollTop: 0 }, 400);
return false;
});
如何在不使用jQuery的情况下为scrollTop设置动画?
答案 0 :(得分:153)
<强> HTML:强>
<button onclick="scrollToTop(1000);"></button>
1 #JavaScript(线性):
function scrollToTop(scrollDuration) {
var scrollStep = -window.scrollY / (scrollDuration / 15),
scrollInterval = setInterval(function(){
if ( window.scrollY != 0 ) {
window.scrollBy( 0, scrollStep );
}
else clearInterval(scrollInterval);
},15);
}
2#JavaScript(轻松进出):
function scrollToTop(scrollDuration) {
const scrollHeight = window.scrollY,
scrollStep = Math.PI / ( scrollDuration / 15 ),
cosParameter = scrollHeight / 2;
var scrollCount = 0,
scrollMargin,
scrollInterval = setInterval( function() {
if ( window.scrollY != 0 ) {
scrollCount = scrollCount + 1;
scrollMargin = cosParameter - cosParameter * Math.cos( scrollCount * scrollStep );
window.scrollTo( 0, ( scrollHeight - scrollMargin ) );
}
else clearInterval(scrollInterval);
}, 15 );
}
注意:强>
由于选民人数众多,我重新检查了几年前写的代码,并尝试对其进行优化。我在代码的底部添加了一些数学解释。
更新(轻松进出):
使用requestAnimationFrame方法完成更流畅的幻灯片/动画。 (在大窗口上发生了一点口吃,因为浏览器必须重绘大面积)
function scrollToTop(scrollDuration) {
var cosParameter = window.scrollY / 2,
scrollCount = 0,
oldTimestamp = performance.now();
function step (newTimestamp) {
scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
if (scrollCount >= Math.PI) window.scrollTo(0, 0);
if (window.scrollY === 0) return;
window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount)));
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanations:
- pi is the length/end point of the cosinus intervall (see above)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the duration
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/