How to get and set the current web page scroll position?

前端 未结 4 1100
无人共我
无人共我 2020-12-02 06:38

How can I get and set the current web page scroll position?

I have a long form which needs to be refreshed based on user actions/input. When this happens, the page

相关标签:
4条回答
  • 2020-12-02 06:45

    You're looking for the document.documentElement.scrollTop property.

    0 讨论(0)
  • 2020-12-02 06:58

    I went with the HTML5 local storage solution... All my links call a function which sets this before changing window.location:

    localStorage.topper = document.body.scrollTop;
    

    and each page has this in the body's onLoad:

      if(localStorage.topper > 0){ 
        window.scrollTo(0,localStorage.topper);
      }
    
    0 讨论(0)
  • 2020-12-02 07:03

    There are some inconsistencies in how browsers expose the current window scrolling coordinates. Google Chrome on Mac and iOS seems to always return 0 when using document.documentElement.scrollTop or jQuery's $(window).scrollTop().

    However, it works consistently with:

    // horizontal scrolling amount
    window.pageXOffset
    
    // vertical scrolling amount
    window.pageYOffset
    
    0 讨论(0)
  • 2020-12-02 07:04

    The currently accepted answer is incorrect - document.documentElement.scrollTop always returns 0 on Chrome. This is because WebKit uses body for keeping track of scrolling, whereas Firefox and IE use html.

    To get the current position, you want:

    document.documentElement.scrollTop || document.body.scrollTop
    

    You can set the current position to 1000px down the page like so:

    document.documentElement.scrollTop = document.body.scrollTop = 1000;
    

    Or, using jQuery (animate it while you're at it!):

    $("html, body").animate({ scrollTop: "1000px" });
    
    0 讨论(0)
提交回复
热议问题