我正在寻找一个简单的,跨浏览器“滚动到顶部”的动画,我可以应用到一个链接。我不想需要一个JS库,如jQuery/Moo等。
// jQuery Equivilant to convert to pure JS...
$('html, body').animate({scrollTop:0}, 400);
对于那些在跳进图书馆之前应该100%学习JS的人来说,我是一个完美的例子。:(
我正在寻找一个简单的,跨浏览器“滚动到顶部”的动画,我可以应用到一个链接。我不想需要一个JS库,如jQuery/Moo等。
// jQuery Equivilant to convert to pure JS...
$('html, body').animate({scrollTop:0}, 400);
对于那些在跳进图书馆之前应该100%学习JS的人来说,我是一个完美的例子。:(
当前回答
我修改了TimWolla的答案,使用二次输入-输出缓和(更流畅一点:)。下面是一个正在运行的示例:在jsFiddle上。这里提供了缓动函数:Robert Penner的缓动函数
document.getElementsByTagName('button')[0].onclick = function () {
scrollTo(document.body, 0, 1250);
}
function scrollTo(element, to, duration) {
var start = element.scrollTop,
change = to - start,
increment = 20;
var animateScroll = function(elapsedTime) {
elapsedTime += increment;
var position = easeInOut(elapsedTime, start, change, duration);
element.scrollTop = position;
if (elapsedTime < duration) {
setTimeout(function() {
animateScroll(elapsedTime);
}, increment);
}
};
animateScroll(0);
}
function easeInOut(currentTime, start, change, duration) {
currentTime /= duration / 2;
if (currentTime < 1) {
return change / 2 * currentTime * currentTime + start;
}
currentTime -= 1;
return -change / 2 * (currentTime * (currentTime - 2) - 1) + start;
}
其他回答
我看到上面大多数/所有的帖子都是用javascript搜索按钮的。这是有效的,只要你只有一个按钮。我建议在按钮内定义一个“onclick”元素。然后,“onclick”将调用该函数,使其滚动。
如果你这样做,你可以使用多个按钮,只要按钮看起来像这样:
<button onclick="scrollTo(document.body, 0, 1250)">To the top</button>
实际上有一个纯javascript的方式来完成这个不使用setTimeout或requestAnimationFrame或jQuery。
简而言之,在scrollView中找到要滚动到的元素,并使用scrollIntoView
el.scrollIntoView({行为:“平滑”});
这是一个普朗克。
JS解决方案w/o jQuery。
element.onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' })
使用这个解决方案
animate(document.documentElement, 'scrollTop', 0, 200);
谢谢
我已经选择了@timwolla answer的@akai版本,并添加了stopAnimation函数作为返回,所以在开始新的动画之前,旧的动画可以停止。
if ( this.stopAnimation )
this.stopAnimation()
this.stopAnimation = scrollTo( el, scrollDestination, 300 )
// definitions
function scrollTo(element, to, duration) {
var start = element.scrollTop,
change = to - start,
increment = 20,
timeOut;
var animateScroll = function(elapsedTime) {
elapsedTime += increment;
var position = easeInOut(elapsedTime, start, change, duration);
element.scrollTop = position;
if (elapsedTime < duration) {
timeOut = setTimeout(function() {
animateScroll(elapsedTime);
}, increment);
}
};
animateScroll(0);
return stopAnimation
function stopAnimation() {
clearTimeout( timeOut )
}
}
function easeInOut(currentTime, start, change, duration) {
currentTime /= duration / 2;
if (currentTime < 1) {
return change / 2 * currentTime * currentTime + start;
}
currentTime -= 1;
return -change / 2 * (currentTime * (currentTime - 2) - 1) + start;
}