Check whether HTML element has scrollbars

前端 未结 11 2092
北海茫月
北海茫月 2020-11-27 11:58

What\'s the fastest way of checking whether an element has scroll bars?

One thing of course is checking whether element is larger than its viewport, which can easily

相关标签:
11条回答
  • 2020-11-27 12:44

    If you need to know if theres a scrollbar present for the whole webpage and with full browser support you can use this:

    const hasScrollbar = document.body.scrollHeight > window.innerHeight
    

    It's important to use window.innerHeight instead of document.body.clientHeight because in some mobile browsers clientHeight will not get the size of the address bar but scrollHeight will, so you get wrong calculations.

    0 讨论(0)
  • 2020-11-27 12:52

    There are several problems in case of checking the existence of scrollbars one of which is that in mac you don't have any visible scrollbar so both all the solutions above wouldn't give you an accurate answer.

    So because the browser's rendering isn't very frequent you can check the having scroll with changing scroll and then setting it back:

    const hasScrollBar = (element) => {
      const {scrollTop} = element;
    
      if(scrollTop > 0) {
        return true;
      }
    
      element.scrollTop += 10;
    
      if(scrollTop === element.scrollTop) {
        return false;
      }
    
      // undoing the change
      element.scrollTop = scrollTop;
      return true;
    };

    0 讨论(0)
  • 2020-11-27 12:53

    Just messing around here as none of the above solutions worked out for me (so far). I have found some success with comparing a Div's scrollheight against its offsetHeight

    var oh = $('#wrapDiv').get(0).offsetHeight;
    var sh = $('#wrapDiv').get(0).scrollHeight;
    

    It seems to give me an acurate comparison...so far. Does someone know if this is legitimate?

    0 讨论(0)
  • 2020-11-27 12:55

    Try:

    For vertical scroll bar

    el.scrollHeight > el.clientHeight

    For horizontal scrollbar

    el.scrollWidth > el.clientWidth

    I know this works for IE8 and Firefox 3.6+ at least.

    0 讨论(0)
  • 2020-11-27 12:56

    none of this answers are correct. you have to use this :

    var div = document.getElementById('container_div_id');
    
    var hasHorizontalScrollbar = (div.offsetWidth > div.clientWidth);
    var hasVerticalScrollbar = (div.offsetHeight > div.clientHeight);
    
    0 讨论(0)
提交回复
热议问题