Check whether HTML element has scrollbars

前端 未结 11 2185
北海茫月
北海茫月 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: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;
    };

提交回复
热议问题