最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

css - How to animate scrolling to top of page using javascript (no jQuery)? - Stack Overflow

programmeradmin2浏览0评论

I would like execute a transition when pressing a button for the webpage to slowly scroll back to the top of the page. I know how to execute a transition using a change in class, but in this instance, how would i do it?

document.documentElement.scrollTop = 0;

I would like execute a transition when pressing a button for the webpage to slowly scroll back to the top of the page. I know how to execute a transition using a change in class, but in this instance, how would i do it?

document.documentElement.scrollTop = 0;
Share Improve this question edited Jul 26, 2018 at 11:10 Alessio Cantarella 5,2113 gold badges29 silver badges36 bronze badges asked Jul 26, 2018 at 10:12 johnDoejohnDoe 79513 silver badges33 bronze badges 1
  • 2 Possible duplicate of Cross browser JavaScript (not jQuery...) scroll to top animation – לבני מלכה Commented Jul 26, 2018 at 10:13
Add a ment  | 

2 Answers 2

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

Works also for any other DOM element. And for horizontal scrolling too.

You can use below code to move the top of the page.

// 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 bees visible when the user starts to scroll the page.</div>

发布评论

评论列表(0)

  1. 暂无评论