Check whether HTML element has scrollbars

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

    I maybe a little late to the party, but...

    I believe you can detect for scrollbars with e.offsetWidth vs. e.clientWidth. Offset width includes borders and scrollbars, padding and width. Client width includes padding and width. Please see:

    https://developer.mozilla.org/en/DOM/element.offsetWidth (second image) https://developer.mozilla.org/en/DOM/element.clientWidth (second image)

    You need to check:

    1. Whether or not the element has overflow set to auto/scroll (including overflowX/Y) using the computed/cascaded/current style.
    2. If the element does have overflow set to auto/scroll. Establish the offsetWidth and clientWidth.
    3. If the clientWidth is less than the offsetWidth - right border (found again through the computed/cascaded/current style), then you know you have a scrollbar.

    Do the same for the vertical (offset/clientHeight).

    IE7 reports a clientHeight of 0 for some elements (I haven't checked why), therefore you always need the first overflow check.

    Hope this helps!

提交回复
热议问题