smooth scroll to top

前端 未结 12 1215
眼角桃花
眼角桃花 2020-12-07 22:58

I\'ve bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 23:44

    You can simply use

    // 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("gotoTop").style.display = "block";
        } else {
            document.getElementById("gotoTop").style.display = "none";
        }
       
    }
    
    // When the user clicks on the button, scroll to the top of the document
    function topFunction() {
     
         $('html, body').animate({scrollTop:0}, 'slow');
    }
    body {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 20px;
    }
    
    #gotoTop {
      display: none;
      position: fixed;
      bottom: 20px;
      right: 30px;
      z-index: 99;
      font-size: 18px;
      border: none;
      outline: none;
      background-color: red;
      color: white;
      cursor: pointer;
      padding: 15px;
      border-radius: 4px;
    }
    
    #gotoTop:hover {
      background-color: #555;
    }
    
    
    
    
    
    Scroll Down
    This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.

提交回复
热议问题