代码之家  ›  专栏  ›  技术社区  ›  johnDoe

如何使用javascript(没有jquery)动画滚动到页面顶部?

  •  0
  • johnDoe  · 技术社区  · 6 年前

    我希望在按下网页的按钮时执行一个转换,以缓慢滚动回页面顶部。我知道如何使用类中的更改来执行转换,但在本例中,我将如何执行转换?

    document.documentElement.scrollTop = 0;
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Alessio Cantarella    6 年前

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

    // 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>
        2
  •  2
  •   Anarion    6 年前
    document.body.scrollIntoView({behavior: 'smooth', block: 'start'});
    

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