Detect if a page has a vertical scrollbar?

后端 未结 13 1826
旧时难觅i
旧时难觅i 2020-11-28 02:17

I just want some simple JQ/JS to check if the current page/window (not a particular element) has a vertical scrollbar.

Googling gives me stuff that seems overly comp

13条回答
  •  没有蜡笔的小新
    2020-11-28 03:14

    I wrote an updated version of Kees C. Bakker's answer:

    const hasVerticalScroll = (node) => {
      if (!node) {
        if (window.innerHeight) {
          return document.body.offsetHeight > window.innerHeight
        }
        return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
          || (document.body.scrollHeight > document.body.offsetHeight)
      }
      return node.scrollHeight > node.offsetHeight
    }
    
    if (hasVerticalScroll(document.querySelector('body'))) {
      this.props.handleDisableDownScrollerButton()
    }
    

    The function returns true or false depending whether the page has a vertical scrollbar or not.

    For example:

    const hasVScroll = hasVerticalScroll(document.querySelector('body'))
    
    if (hasVScroll) {
      console.log('HAS SCROLL', hasVScroll)
    }
    

提交回复
热议问题