How to get scrollbar position with Javascript?

前端 未结 9 2245
自闭症患者
自闭症患者 2020-11-22 11:23

I\'m trying to detect the position of the browser\'s scrollbar with JavaScript to decide where in the page the current view is. My guess is that I have to detect where the t

相关标签:
9条回答
  • 2020-11-22 11:55
    document.getScroll = function() {
        if (window.pageYOffset != undefined) {
            return [pageXOffset, pageYOffset];
        } else {
            var sx, sy, d = document,
                r = d.documentElement,
                b = d.body;
            sx = r.scrollLeft || b.scrollLeft || 0;
            sy = r.scrollTop || b.scrollTop || 0;
            return [sx, sy];
        }
    }
    

    returns an array with two integers- [scrollLeft, scrollTop]

    0 讨论(0)
  • 2020-11-22 12:00

    Here is the other way to get scroll position

    const getScrollPosition = (el = window) => ({
      x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
      y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
    });
    
    0 讨论(0)
  • 2020-11-22 12:02

    I did this for a <div> on Chrome.

    element.scrollTop - is the pixels hidden in top due to the scroll. With no scroll its value is 0.

    element.scrollHeight - is the pixels of the whole div.

    element.clientHeight - is the pixels that you see in your browser.

    var a = element.scrollTop;
    

    will be the position.

    var b = element.scrollHeight - element.clientHeight;
    

    will be the maximum value for scrollTop.

    var c = a / b;
    

    will be the percent of scroll [from 0 to 1].

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