Cross-browser method for detecting the scrollTop of the browser window

前端 未结 11 1735
孤街浪徒
孤街浪徒 2020-11-27 12:38

What is the best cross-browser way to detect the scrollTop of the browser window? I prefer not to use any pre-built code libraries because this is a very simple script, and

11条回答
  •  北海茫月
    2020-11-27 13:13

    I believe the best way to get scrollTop in modern browsers is to use

    const scrollTop = document.scrollingElement.scrollTop
    

    if this doesn't work you could also try

    const scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop, document.scrollingElement.scrollTop)
    

提交回复
热议问题