How can I check if a scrollbar is visible?

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

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

For example:

HTML

19条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 15:28

    You can do this using a combination of the Element.scrollHeight and Element.clientHeight attributes.

    According to MDN:

    The Element.scrollHeight read-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar. It includes the element padding but not its margin.

    And:

    The Element.clientHeight read-only property returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin.

    clientHeight can be calculated as CSS height + CSS padding - height of horizontal scrollbar (if present).

    Therefore, the element will display a scrollbar if the scroll height is greater than the client height, so the answer to your question is:

    function scrollbarVisible(element) {
      return element.scrollHeight > element.clientHeight;
    }
    

提交回复
热议问题