Detect if a page has a vertical scrollbar?

后端 未结 13 1825
旧时难觅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 02:55

    I found vanila solution

    var hasScrollbar = function() {
      // The Modern solution
      if (typeof window.innerWidth === 'number')
        return window.innerWidth > document.documentElement.clientWidth
    
      // rootElem for quirksmode
      var rootElem = document.documentElement || document.body
    
      // Check overflow style property on body for fauxscrollbars
      var overflowStyle
    
      if (typeof rootElem.currentStyle !== 'undefined')
        overflowStyle = rootElem.currentStyle.overflow
    
      overflowStyle = overflowStyle || window.getComputedStyle(rootElem, '').overflow
    
        // Also need to check the Y axis overflow
      var overflowYStyle
    
      if (typeof rootElem.currentStyle !== 'undefined')
        overflowYStyle = rootElem.currentStyle.overflowY
    
      overflowYStyle = overflowYStyle || window.getComputedStyle(rootElem, '').overflowY
    
      var contentOverflows = rootElem.scrollHeight > rootElem.clientHeight
      var overflowShown    = /^(visible|auto)$/.test(overflowStyle) || /^(visible|auto)$/.test(overflowYStyle)
      var alwaysShowScroll = overflowStyle === 'scroll' || overflowYStyle === 'scroll'
    
      return (contentOverflows && overflowShown) || (alwaysShowScroll)
    }

提交回复
热议问题