Javascript 检测DIV是否有滚动条
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10948044/
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
Detect if the DIV have scroll bar or not
提问by Wasim Shaikh
Possible Duplicate:
Detecting presence of a scroll bar in a DIV using jQuery?
There is markup as below,
有如下标记,
<div class="content">Lorem</div>
<div class="content">Lorem Iorem Lorem Iorem Lorem Iorem Lorem Iorem Lorem IoremLorem Iorem Lorem Iorem Lorem Iorem</div>
<div class="content">Lorem</div>
<div class="content">Lorem</div>
If content have scroll bar, then it should add class to that div like "scroll-image".
如果内容有滚动条,那么它应该像“scroll-image”一样向那个 div 添加类。
Height can be different for DIVs. Any jQuery solution for this.
DIV 的高度可以不同。任何 jQuery 解决方案。
回答by 472084
(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..
Taken from How can I check if a scrollbar is visible?
回答by Sarfraz
You need to compare scrollHeight
with height
of the element like this:
您需要scrollHeight
与这样height
的元素进行比较:
$('.content').each(function(){
if ($(this)[0].scrollHeight > $(this).height()) {
$(this).addClass('scroll-image');
}
});
回答by altschuler
As esailija said, duplicate of: Detecting presence of a scroll bar in a DIV using jQuery?
正如esailija所说,重复:使用jQuery检测DIV中滚动条的存在?
The solution there was the following
解决方案如下
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 Johan
(function($) {
$.fn.hasScrollBar = function() {
return this.get(0).scrollHeight > this.height();
}
})(jQuery);
$('div').hasScrollBar(); //return true if it has one
Source: How can I check if a scrollbar is visible?
来源:如何检查滚动条是否可见?