Check whether HTML element has scrollbars

前端 未结 11 2183
北海茫月
北海茫月 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:38

    Here is yet another solution:

    As a few people pointed out, simply comparing offsetHeight and scrollHeight is not enough since they differ on elements with overflow hidden, etc., that still don't have scrollbars. So here I'm also checking if overflow is scroll or auto on the computed styles for the element:

    var isScrollable = function(node) {
      var overflowY = window.getComputedStyle(node)['overflow-y'];
      var overflowX = window.getComputedStyle(node)['overflow-x'];
      return {
        vertical: (overflowY === 'scroll' || overflowY === 'auto') && node.scrollHeight > node.clientHeight,
        horizontal: (overflowX === 'scroll' || overflowX === 'auto') && node.scrollWidth > node.clientWidth,
      };
    }
    

提交回复
热议问题