如何使回到顶部链接快速滚动到顶部而不是立即跳跃

时间:2017-11-19 20:01:44

标签: javascript html css

在我的页脚中,我有一个"返回顶部"按钮,它立即跳转到页面顶部。我怎样才能使它快速滚动到顶部呢?

1 个答案:

答案 0 :(得分:-1)

你可以添加这些javascript函数:

function ScrollTo(name) {
   ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() {
      ScrollToResolver(elem);
    }, "100");
  } else {
    elem.lastjump = null;
  }
}

并在按钮上添加此函数调用:

<button onclick="ScrollTo('top')">Back to Top</button>

其中内容的非常有元素具有“top”类