是否有可能检查溢出:自动的一个div?

例如:

HTML

<div id="my_div" style="width: 100px; height:100px; overflow:auto;" class="my_class"> 
  * content
</div>

JQUERY

$('.my_class').live('hover', function (event)
{
    if (event.type == 'mouseenter')
    {
         if( ...  if scrollbar visible ? ... )
         {
            alert('true'):
         }
         else
         {
            alert('false'):
         }
    }

});

有时内容很短(没有滚动条),有时内容很长(滚动条可见)。


当前回答

一个小插件。

(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);

像这样用,

$('#my_div1').hasScrollBar(); // returns true if there's a `vertical` scrollbar, false otherwise..

测试工作在Firefox, Chrome, IE6,7,8

但在主体标签选择器上不能正常工作

demo


Edit

我发现,当你有水平滚动条,导致垂直滚动条出现,这个功能不工作....

我找到了另一个解决办法…使用clientHeight

return this.get(0).scrollHeight > this.get(0).clientHeight;

其他回答

这里是Evan的答案的改进版本,它似乎正确地解释了溢出逻辑。

            function element_scrollbars(node) {
                var element = $(node);
                var overflow_x = element.css("overflow-x");
                var overflow_y = element.css("overflow-y");
                var overflow = element.css("overflow");
                if (overflow_x == "undefined") overflow_x == "";
                if (overflow_y == "undefined") overflow_y == "";
                if (overflow == "undefined") overflow == "";
                if (overflow_x == "") overflow_x = overflow;
                if (overflow_y == "") overflow_y = overflow;
                var scrollbar_vertical = (
                    (overflow_y == "scroll")
                    || (
                        (
                            (overflow_y == "hidden")
                            || (overflow_y == "visible")
                        )
                        && (
                            (node.scrollHeight > node.clientHeight)
                        )
                    )
                );
                var scrollbar_horizontal = (
                    (overflow_x == "scroll")
                    || (
                        (
                            (overflow_x == "hidden")
                            || (overflow_x == "visible")
                        )
                        && (
                            (node.scrollWidth > node.clientWidth)
                        )
                    )
                );
                return {
                    vertical: scrollbar_vertical,
                    horizontal: scrollbar_horizontal
                };
            }

上面提供的解决方案将在大多数情况下工作,但检查scrollHeight和溢出有时是不够的,可以失败的body和html元素如下所示: https://codepen.io/anon/pen/EvzXZw

1. 解决方案-检查元素是否可滚动:

function isScrollableY (element) {
  return !!(element.scrollTop || (++element.scrollTop && element.scrollTop--));
}

注意:带有overflow: hidden的元素也被视为可滚动的(更多信息),所以如果需要,你也可以添加一个条件:

function isScrollableY (element) {
    let style = window.getComputedStyle(element);
    return !!(element.scrollTop || (++element.scrollTop && element.scrollTop--)) 
           && style["overflow"] !== "hidden" && style["overflow-y"] !== "hidden";
}

据我所知,这种方法只有在元素具有滚动行为:平滑时才会失败。

解释:诀窍在于,向下滚动和返回的尝试不会被浏览器渲染。最上面的函数也可以写成这样:

function isScrollableY (element) { // if scrollTop is not 0 / larger than 0, then the element is scrolled and therefore must be scrollable // -> true if (element.scrollTop === 0) { // if the element is zero it may be scrollable // -> try scrolling about 1 pixel element.scrollTop++; // if the element is zero then scrolling did not succeed and therefore it is not scrollable // -> false if (element.scrollTop === 0) return false; // else the element is scrollable; reset the scrollTop property // -> true element.scrollTop--; } return true; }

2. 解决方案——做所有必要的检查:

function isScrollableY (element) {
  const style = window.getComputedStyle(element);
  
  if (element.scrollHeight > element.clientHeight &&
      style["overflow"] !== "hidden" && style["overflow-y"] !== "hidden" &&
      style["overflow"] !== "clip" && style["overflow-y"] !== "clip"
  ) {
    if (element === document.scrollingElement) return true;
    else if (style["overflow"] !== "visible" && style["overflow-y"] !== "visible") {
      // special check for body element (https://drafts.csswg.org/cssom-view/#potentially-scrollable)
      if (element === document.body) {
        const parentStyle = window.getComputedStyle(element.parentElement);
        if (parentStyle["overflow"] !== "visible" && parentStyle["overflow-y"] !== "visible" &&
            parentStyle["overflow"] !== "clip" && parentStyle["overflow-y"] !== "clip"
        ) {
          return true;
        }
      }
      else return true;
    }
  }
  
  return false;
}

至少在新版本的Chrome、Edge、Firefox和Opera上都可以使用。

使用JQuery……

设置这个函数来修复页脚:

function fixFooterCaller()
{
    const body = $('body');
    const footer = $('body footer');

    return function ()
    {
        // If the scroll bar is visible
        if ($(document).height() > $(window).height())
        {
            // Reset
            footer.css('position', 'inherit');
            // Erase the padding added in the above code
            body.css('padding-bottom', '0');
        }
        // If the scrollbar is NOT visible
        else
        {
            // Make it fixed at the bottom
            footer.css('position', 'fixed');
            // And put a padding to the body as the size of the footer
            // This makes the footer do not cover the content and when
            // it does, this event fix it
            body.css('padding-bottom', footer.outerHeight());
        }
    }
}

它返回一个函数。这样做只是为了设置一次正文和页脚。

然后,在文档准备好时设置这个。

$(document).ready(function ()
{
    const fixFooter = fixFooterCaller();

    // Put in a timeout call instead of just call the fixFooter function
    // to prevent the page elements needed don't be ready at this time
    setTimeout(fixFooter, 0);
    // The function must be called every time the window is resized
    $(window).resize(fixFooter);
});

添加这个到你的页脚css:

footer {
    bottom: 0;
}

无框架JavaScript方法,检查垂直和水平

 /*
 * hasScrollBars
 * 
 * Checks to see if an element has scrollbars
 * 
 * @returns {object}
 */
Element.prototype.hasScrollBars = function() {
    return {"vertical": this.scrollHeight > this.style.height, "horizontal": this.scrollWidth > this.style.width};
}

像这样使用它

if(document.getElementsByTagName("body")[0].hasScrollBars().vertical){
            alert("vertical");
}

        if(document.getElementsByTagName("body")[0].hasScrollBars().horizontal){
            alert("horizontal");
}

您可以使用Element的组合来做到这一点。scrollHeight和Element。clientHeight属性。

根据MDN:

元素。scrollHeight只读属性是对元素内容高度的测量,包括由于溢出而在屏幕上不可见的内容。scrollHeight值等于元素为了适应视点中的所有内容而不使用垂直滚动条所需的最小clientHeight。它包括元素的填充,但不包括它的边距。

And:

元素。clientHeight只读属性返回元素的内部高度(以像素为单位),包括填充,但不包括水平滚动条高度、边框或边距。 clientHeight可以计算为CSS高度+ CSS填充-水平滚动条的高度(如果存在的话)。

因此,如果滚动高度大于客户端高度,元素将显示滚动条,所以你的问题的答案是:

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