Scroll to the top of the page using JavaScript?

后端 未结 30 1095
借酒劲吻你
借酒劲吻你 2020-11-22 03:18

How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I\'m not looking to achieve smooth scroll

30条回答
  •  遇见更好的自我
    2020-11-22 03:34

    Motivation

    This simple solution works natively and implements a smooth scroll to any position.

    It avoids using anchor links (those with #) that, in my opinion, are useful if you want to link to a section, but are not so comfortable in some situations, specially when pointing to top which could lead to two different URLs pointing to the same location (http://www.example.org and http://www.example.org/#).

    Solution

    Put an id to the tag you want to scroll to, for example your first section, which answers this question, but the id could be placed everywhere in the page.

    
      

    Then as a button you can use a link, just edit the onclick attribute with a code like this.

    Click me
    

    Where the argument of document.getElementById is the id of the tag you want to scroll to after click.

提交回复
热议问题