如何检查滚动条是否可见?

Pet*_*ter 260 jquery scroll overflow

是否有可能检查overflow:autodiv?

例如:

HTML

<div id="my_div" style="width: 100px; height:100px; overflow:auto;" class="my_class"> 
  * content
</div>
Run Code Online (Sandbox Code Playgroud)

JQUERY

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

});
Run Code Online (Sandbox Code Playgroud)

有时内容较短(无滚动条),有时长(滚动条可见).

Rei*_*gel 365

一个小插件.

(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

像这样使用它,

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

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

但在body标签选择器上无法正常工作

演示


编辑

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

我找到了另一个解决方案......使用 clientHeight

return this.get(0).scrollHeight > this.get(0).clientHeight;
Run Code Online (Sandbox Code Playgroud)

  • 如果你有填充,你需要使用`> this.innerHeight();`http://jsfiddle.net/p3FFL/210/ (21认同)
  • 请注意,在Mac上,滚动条会浮动在内容上,并在不使用时消失.在Windows上,它始终可见并占用水平空间.因此,仅仅因为可以滚动内容(该功能检测到的内容)并不意味着必须存在滚动条. (8认同)
  • 如果有办法让它与身体一起工作? (5认同)
  • 这有一个问题,如果还存在水平滚动条,那么即使垂直滚动条存在,直到高度已被水平滚动条高度缩小,这将返回false. (2认同)
  • (function($){$ .fn.hasScrollBar = function(){return this.get(0).scrollWidth> this.width); ()jQuery); 这适用于水平覆盖.适合在iframe中检查网站上的移动响应能力. (2认同)
  • scrollHeight &gt; clientHeight,这适用于所有情况,包括填充、边框 (2认同)

小智 54

也许更简单的解决方案.

if ($(document).height() > $(window).height()) {
    // scrollbar
}
Run Code Online (Sandbox Code Playgroud)

  • 这假设滚动条在窗口上而不是 div 元素。建议修改参考建议:“如果你只需要在主窗口测试滚动条,你可以尝试:” (6认同)

kpu*_*ll1 41

我应该改变Reigel所说的一点:

(function($) {
    $.fn.hasScrollBar = function() {
        return this[0] ? this[0].scrollHeight > this.innerHeight() : false;
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

innerHeight计算控件的高度及其顶部和底部填充

  • 我认为这应该被指定为正确答案。这适用于FF35,IE11和Chrome39。 (2认同)

Aje*_*i32 37

您可以使用Element.scrollHeightElement.clientHeight属性的组合来完成此操作.

据MDN称:

所述Element.scrollHeight只读属性是一个元素的含量的高度的测量,包括由于溢出内容在屏幕上不可见的.scrollHeight值等于元素在不使用垂直滚动条的情况下拟合视点中的所有内容所需的最小clientHeight.它包括元素填充但不包括其边距.

和:

所述Element.clientHeight只读属性返回元素的以像素为单位,包括填充但不水平滚动条高度,边框或余量内的高度.

clientHeight可以计算为CSS高度+ CSS填充 - 水平滚动条的高度(如果存在).

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

function scrollbarVisible(element) {
  return element.scrollHeight > element.clientHeight;
}
Run Code Online (Sandbox Code Playgroud)

  • 投票支持不蹩脚和使用框架/库。 (8认同)
  • 例如:https://github.com/twbs/bootstrap/blob/master/js/modal.js#L242和+1表示MDN引用和解释! (2认同)
  • 小心 - 这会导致回流,从而降低性能。https://gist.github.com/paulirish/5d52fb081b3570c81e3a (2认同)

the*_*ess 24

这扩展了@Reigel的答案.它将返回水平或垂直滚动​​条的答案.

(function($) {
    $.fn.hasScrollBar = function() {
        var e = this.get(0);
        return {
            vertical: e.scrollHeight > e.clientHeight,
            horizontal: e.scrollWidth > e.clientWidth
        };
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

例:

element.hasScrollBar()             // Returns { vertical: true/false, horizontal: true/false }
element.hasScrollBar().vertical    // Returns true/false
element.hasScrollBar().horizontal  // Returns true/false
Run Code Online (Sandbox Code Playgroud)


Bol*_*wyn 11

你需要element.scrollHeight.比较它$(element).height().


the*_*eer 7

我做了一个新的自定义:jQuery的伪选择器来测试一个项是否具有以下css属性之一:

  1. 溢出:[scroll | auto]
  2. overflow-x:[scroll | auto]
  3. overflow-y:[scroll | auto]

我想找到另一个元素最接近的可滚动父类,所以我还写了另一个小jQuery插件来找到最接近溢出的父类.

这个解决方案可能不是最好的,但它似乎确实有效.我将它与$ .scrollTo插件结合使用.有时我需要知道元素是否在另一个可滚动容器中.在这种情况下,我想滚动父可滚动元素与窗口.

我可能应该将它包装在一个插件中并添加psuedo选择器作为插件的一部分,以及公开"最接近"的方法来查找最近(父)可滚动容器.

Anywho ....在这里.

$ .isScrollable jQuery插件:

$.fn.isScrollable = function(){
    var elem = $(this);
    return (
    elem.css('overflow') == 'scroll'
        || elem.css('overflow') == 'auto'
        || elem.css('overflow-x') == 'scroll'
        || elem.css('overflow-x') == 'auto'
        || elem.css('overflow-y') == 'scroll'
        || elem.css('overflow-y') == 'auto'
    );
};
Run Code Online (Sandbox Code Playgroud)

$(':scrollable')jQuery伪选择器:

$.expr[":"].scrollable = function(a) {
    var elem = $(a);
    return elem.isScrollable();
};
Run Code Online (Sandbox Code Playgroud)

$ .scrollableparent()jQuery插件:

$.fn.scrollableparent = function(){
    return $(this).closest(':scrollable') || $(window); //default to $('html') instead?
};
Run Code Online (Sandbox Code Playgroud)

实施非常简单

//does a specific element have overflow scroll?
var somedivIsScrollable = $(this).isScrollable();
//use :scrollable psuedo selector to find a collection of child scrollable elements
var scrollableChildren = $(this).find(':scrollable');
//use $.scrollableparent to find closest scrollable container
var scrollableparent = $(this).scrollableparent();
Run Code Online (Sandbox Code Playgroud)

更新:我发现Robert Koritnik已经提出了一个更强大的:可滚动的伪选择器,它将识别可滚动容器的可滚动轴和高度,作为他的$ .scrollintoview()jQuery插件的一部分.scrollintoview插件

这是他的花式伪选择器(道具):

    $.extend($.expr[":"], {

    scrollable: function (element, index, meta, stack) {

        var direction = converter[typeof (meta[3]) === "string" && meta[3].toLowerCase()] || converter.both;

        var styles = (document.defaultView && document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(element, null) : element.currentStyle);

        var overflow = {

            x: scrollValue[styles.overflowX.toLowerCase()] || false,

            y: scrollValue[styles.overflowY.toLowerCase()] || false,

            isRoot: rootrx.test(element.nodeName)

        };



        // check if completely unscrollable (exclude HTML element because it's special)

        if (!overflow.x && !overflow.y && !overflow.isRoot)

        {

            return false;

        }



        var size = {

            height: {

                scroll: element.scrollHeight,

                client: element.clientHeight

            },

            width: {

                scroll: element.scrollWidth,

                client: element.clientWidth

            },

            // check overflow.x/y because iPad (and possibly other tablets) don't dislay scrollbars

            scrollableX: function () {

                return (overflow.x || overflow.isRoot) && this.width.scroll > this.width.client;

            },

            scrollableY: function () {

                return (overflow.y || overflow.isRoot) && this.height.scroll > this.height.client;

            }

        };

        return direction.y && size.scrollableY() || direction.x && size.scrollableX();

    }

});
Run Code Online (Sandbox Code Playgroud)


小智 6

上面的第一个解决方案仅适用于IE.上面的第二个解决方案仅适用于FF

这两种功能的组合适用于两种浏览器:

//Firefox Only!!
if ($(document).height() > $(window).height()) {
    // has scrollbar
    $("#mtc").addClass("AdjustOverflowWidth");
    alert('scrollbar present - Firefox');
} else {
    $("#mtc").removeClass("AdjustOverflowWidth");
}

//Internet Explorer Only!!
(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.innerHeight();
    }
})(jQuery);
if ($('#monitorWidth1').hasScrollBar()) {
    // has scrollbar
    $("#mtc").addClass("AdjustOverflowWidth");
    alert('scrollbar present - Internet Exploder');
} else {
    $("#mtc").removeClass("AdjustOverflowWidth");
}?
Run Code Online (Sandbox Code Playgroud)
  • 准备好文件包装
  • monitorWidth1:溢出设置为auto的div
  • mtc:monitorWidth1中的容器div
  • AdjustOverflowWidth:当滚动条处于活动状态时应用于#mtc div的css类*使用警报测试跨浏览器,然后注释掉最终的生产代码.

HTH


B T*_*B T 6

呃,这里每个人的答案都不完整,请让我们停止在 SO 答案中使用 jquery。如果您需要有关 jquery 的信息,请查看 jquery 的文档。

这是一个通用的纯javascript函数,用于以完整的方式测试元素是否具有滚动条:

// dimension - Either 'y' or 'x'
// computedStyles - (Optional) Pass in the domNodes computed styles if you already have it (since I hear its somewhat expensive)
function hasScrollBars(domNode, dimension, computedStyles) {
    dimension = dimension.toUpperCase()
    if(dimension === 'Y') {
        var length = 'Height'
    } else {
        var length = 'Width'
    }

    var scrollLength = 'scroll'+length
    var clientLength = 'client'+length
    var overflowDimension = 'overflow'+dimension

    var hasVScroll = domNode[scrollLength] > domNode[clientLength]


    // Check the overflow and overflowY properties for "auto" and "visible" values
    var cStyle = computedStyles || getComputedStyle(domNode)
    return hasVScroll && (cStyle[overflowDimension] == "visible"
                         || cStyle[overflowDimension] == "auto"
                         )
          || cStyle[overflowDimension] == "scroll"
}
Run Code Online (Sandbox Code Playgroud)

  • @kpull1 太多人在他们遇到的每个 JavaScript 问题上都标记了 jQuery。这个问题与 jQuery 的关系为 0。* 没有 * jQuery 文档的任何部分都有答案,因为 jQuery 不这样做,也不应该这样做。 (7认同)
  • 为什么要避免在标记为 jquery 的问题上使用 jquery?请添加指向您提到的 jquery 文档部分的链接。 (5认同)

Yai*_*evy 5

(scrollWidth/Height - clientWidth/Height)是滚动条存在的一个很好的指标,但它会在很多场合给你一个"误报"的答案.如果你需要准确我会建议使用以下功能.而不是试图猜测元素是否可滚动 - 你可以滚动它...

function isScrollable( el ){
  var y1 = el.scrollTop;
  el.scrollTop  += 1;
  var y2 = el.scrollTop;
  el.scrollTop  -= 1;
  var y3 = el.scrollTop;
  el.scrollTop   = y1;
  var x1 = el.scrollLeft;
  el.scrollLeft += 1;
  var x2 = el.scrollLeft;
  el.scrollLeft -= 1;
  var x3 = el.scrollLeft;
  el.scrollLeft  = x1;
  return {
    horizontallyScrollable: x1 !== x2 || x2 !== x3,
    verticallyScrollable: y1 !== y2 || y2 !== y3
  }
}
function check( id ){
  alert( JSON.stringify( isScrollable( document.getElementById( id ))));
}
Run Code Online (Sandbox Code Playgroud)
#outer1, #outer2, #outer3 {
  background-color: pink;
  overflow: auto;
  float: left;
}
#inner {
  width:  150px;
  height: 150px;
}
button {  margin: 2em 0 0 1em; }
Run Code Online (Sandbox Code Playgroud)
<div id="outer1" style="width: 100px; height: 100px;">
  <div id="inner">
    <button onclick="check('outer1')">check if<br>scrollable</button>
  </div>
</div>
<div id="outer2" style="width: 200px; height: 100px;">
  <div id="inner">
    <button onclick="check('outer2')">check if<br>scrollable</button>
  </div>
</div>
<div id="outer3" style="width: 100px; height: 180px;">
  <div id="inner">
    <button onclick="check('outer3')">check if<br>scrollable</button>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)