在纯javascript中滚动到顶部动画?不能使用jQuery

时间:2015-08-03 17:09:37

标签: javascript jquery

有一种简单的方法可以转换它:

$("html, body").animate({ scrollTop: $(document).height() }, 10000);

进入纯JavaScript?我需要能够在我没有jQuery可用的设置中运行js。有任何想法吗?感谢。

1 个答案:

答案 0 :(得分:1)

您可以通过在一段时间内逐步更改scrollTop property来完成此操作。



var scrollingElement = document.body;
var endScrollPosition = scrollingElement.clientHeight;
var timeInMS = 10000;
var startTime = new Date().getTime();
var endTime = new Date(new Date().getTime() + timeInMS).getTime() - startTime;

// Use requestAnimationFrame to ensure a smooth transition
requestAnimationFrame(function animate() {
  // Determine what percentage of the total time has passed
  var now = new Date().getTime() - startTime;
  var ratio = now / endTime;
  if (ratio > 1) {
    ratio = 1;
  }
  
  scrollingElement.scrollTop = endScrollPosition * ratio;
  if (ratio < 1) {
    requestAnimationFrame(animate);
  }
});
&#13;
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
<h1>Padding</h1>
&#13;
&#13;
&#13;