Set scroll position

后端 未结 4 1866
走了就别回头了
走了就别回头了 2020-12-04 17:24

I\'m trying to set the scroll position on a page so the scroller is scrolled all the way to the top.

I think I need something like this but it\'s not working:

相关标签:
4条回答
  • 2020-12-04 17:42

    You can use window.scrollTo(), like this:

    window.scrollTo(0, 0); // values are x,y-offset
    
    0 讨论(0)
  • 2020-12-04 17:46

    ... Or just replace body by documentElement:

    document.documentElement.scrollTop = 0;
    
    0 讨论(0)
  • 2020-12-04 17:48

    Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

    var el = document.getElementById("myel"); // Or whatever method to get the element
    
    // To set the scroll
    el.scrollTop = 0;
    el.scrollLeft = 0;
    
    // To increment the scroll
    el.scrollTop += 100;
    el.scrollLeft += 100;
    

    You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

    Object.defineProperty(HTMLElement.prototype, "scrollTo", {
        value: function(x, y) {
            el.scrollTop = y;
            el.scrollLeft = x;
        },
        enumerable: false
    });
    
    Object.defineProperty(HTMLElement.prototype, "scrollBy", {
        value: function(x, y) {
            el.scrollTop += y;
            el.scrollLeft += x;
        },
        enumerable: false
    });
    

    so you can do:

    var el = document.getElementById("myel"); // Or whatever method to get the element, again
    
    // To set the scroll
    el.scrollTo(0, 0);
    
    // To increment the scroll
    el.scrollBy(100, 100);
    

    NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

    0 讨论(0)
  • 2020-12-04 17:56

    Also worth noting window.scrollBy(dx,dy) (ref)

    0 讨论(0)
提交回复
热议问题