How to jump to top of browser page

后端 未结 8 842
后悔当初
后悔当初 2020-12-22 15:48

I\'m writing a modal popup and I need the browser to jump to the top of the screen when the open modal button is pressed. Is there a way to scroll the browser to the top usi

8条回答
  •  执笔经年
    2020-12-22 16:23

    // 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() {
     
         $('html, body').animate({scrollTop:0}, 'slow');
    }
    body {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 20px;
    }
    
    #myBtn {
      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;
    }
    
    #myBtn: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.

提交回复
热议问题