Check whether HTML element has scrollbars

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

    This may seem (or be) a little hackish, but you could test the scrollTop and scrollLeft properties.

    If they're greater than 0, you know there are scrollbars. If they're 0, then set them to 1, and test them again to see if you get a result of 1. Then set them back to 0.

    Example: http://jsfiddle.net/MxpR6/1/

    function hasScroll(el, direction) {
        direction = (direction === 'vertical') ? 'scrollTop' : 'scrollLeft';
        var result = !! el[direction];
    
        if (!result) {
            el[direction] = 1;
            result = !!el[direction];
            el[direction] = 0;
        }
        return result;
    }
    
    alert('vertical? ' + hasScroll(document.body, 'vertical'));
    alert('horizontal? ' + hasScroll(document.body, 'horizontal'));
    

    I believe there's a different property for IE, so I'll update in a minute with that.

    EDIT: Appears as though IE may support this property. (I can't test IE right now.)

    http://msdn.microsoft.com/en-us/library/ms534618(VS.85).aspx

提交回复
热议问题