如何使用javascript(无jQuery)动画化滚动到页面顶部的动画?

时间:2018-07-26 10:12:16

标签: javascript css transition

我想在按下按钮以使网页缓慢滚动回到页面顶部时执行过渡。我知道如何使用类中的更改执行过渡,但是在这种情况下,我将如何做?

document.documentElement.scrollTop = 0;

2 个答案:

答案 0 :(得分:2)

document.body.scrollIntoView({behavior: 'smooth', block: 'start'});

也可用于任何其他DOM元素。还有水平滚动。

答案 1 :(得分:1)

您可以使用以下代码移动页面顶部。

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("myBtn").style.display = "block";
  } else {
    document.getElementById("myBtn").style.display = "none";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 20px;
  background: #ffffff;
}

#myBtn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  background-color: red;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}

#myBtn:hover {
  background-color: #555;
}
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
<div style="padding:30px">Scroll Down</div>
<div style="padding:30px 30px 700px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>