Javascript 使用 jQuery 检测 DIV 中是否存在滚动条?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2647761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting presence of a scroll bar in a DIV using jQuery?
提问by 7wp
I want to detect the presence of a scroll bar in a DIV using jQuery. I was thinking to use $('div').scrollTop()but that returns 0 in both cases when the scroll bar is at the top and when there is no scroll bar at all.
我想使用 jQuery 检测 DIV 中是否存在滚动条。我想使用$('div').scrollTop()但在滚动条位于顶部和根本没有滚动条的两种情况下都返回 0。
Any ideas guys?
有什么想法吗?
回答by bobince
Assuming overflowon the div is auto:
假设overflow在 div 上是auto:
var div= document.getElementById('something'); // need real DOM Node, not jQuery wrapper
var hasVerticalScrollbar= div.scrollHeight>div.clientHeight;
var hasHorizontalScrollbar= div.scrollWidth>div.clientWidth;
回答by PlugTrade.com
// plugtrade.com - jQuery detect vertical scrollbar function //
(function($) {
$.fn.has_scrollbar = function() {
var divnode = this.get(0);
if(divnode.scrollHeight > divnode.clientHeight)
return true;
}
})(jQuery);
example:
例子:
if($('#mydiv').has_scrollbar()) { /* do something */ }
回答by Musikero31
I will revise what bobince mentioned above since you are asking for jQuery
由于您要求使用 jQuery,我将修改上面提到的 bobince
var div= $('#something');
var hasVerticalScrollbar= div[0].scrollHeight > div[0].clientHeight;
var hasHorizontalScrollbar= div[0].scrollWidth > div[0].clientWidth;
This is because scrollHeightand scrollWidthare DOM properties.
这是因为scrollHeight和scrollWidth是 DOM 属性。
回答by 7wp
Well I ended up finding a solution by doing the following:
好吧,我最终通过执行以下操作找到了解决方案:
Wrap the content that grows with a DIV, then I detect if a (vertical) scroll bar is present by comparing the height of wrapperDivwith the height of containerDiv(which normally has the scroll bar if the content is too large).
用 DIV 包装增长的内容,然后我通过比较 的高度wrapperDiv与 的高度containerDiv(如果内容太大,通常有滚动条)来检测是否存在(垂直)滚动条。
If the height of wrapperDivis bigger than the height of containerDivthen there is a scroll bar, if it is smaller, then there is no scroll bar.
如果高度wrapperDiv大于高度containerDiv则有滚动条,如果小于高度则没有滚动条。
<DIV id="containerDiv" style="width:100px;height:100px;overflow:auto;">
<DIV id="wrapperDiv">
.... content here...
</DIV>
</DIV>

