How can I check if a scrollbar is visible?

后端 未结 19 2879
情话喂你
情话喂你 2020-11-22 14:39

Is it possible to check the overflow:auto of a div?

For example:

HTML

19条回答
  •  温柔的废话
    2020-11-22 15:33

    Ugh everyone's answers on here are incomplete, and lets stop using jquery in SO answers already please. Check jquery's documentation if you want info on jquery.

    Here's a generalized pure-javascript function for testing whether or not an element has scrollbars in a complete way:

    // dimension - Either 'y' or 'x'
    // computedStyles - (Optional) Pass in the domNodes computed styles if you already have it (since I hear its somewhat expensive)
    function hasScrollBars(domNode, dimension, computedStyles) {
        dimension = dimension.toUpperCase()
        if(dimension === 'Y') {
            var length = 'Height'
        } else {
            var length = 'Width'
        }
    
        var scrollLength = 'scroll'+length
        var clientLength = 'client'+length
        var overflowDimension = 'overflow'+dimension
    
        var hasVScroll = domNode[scrollLength] > domNode[clientLength]
    
    
        // Check the overflow and overflowY properties for "auto" and "visible" values
        var cStyle = computedStyles || getComputedStyle(domNode)
        return hasVScroll && (cStyle[overflowDimension] == "visible"
                             || cStyle[overflowDimension] == "auto"
                             )
              || cStyle[overflowDimension] == "scroll"
    }
    

提交回复
热议问题