jQuery 如何检查滚动条是否可见?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4814398/
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
How can I check if a scrollbar is visible?
提问by Peter
Is it possible to check the overflow:auto
of a div?
是否可以检查overflow:auto
div的?
For example:
例如:
HTML
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'):
}
}
});
Sometimes is the content short (no scrollbar) and sometimes long (scrollbar visible).
有时内容很短(没有滚动条),有时很长(滚动条可见)。
回答by Reigel
a little plugin for it.
一个小插件。
(function($) {
$.fn.hasScrollBar = function() {
return this.get(0).scrollHeight > this.height();
}
})(jQuery);
use it like this,
像这样使用它,
$('#my_div1').hasScrollBar(); // returns true if there's a `vertical` scrollbar, false otherwise..
tested working on Firefox, Chrome, IE6,7,8
已在 Firefox、Chrome、IE6、7、8 上测试
but not working properly on body
tag selector
但在body
标签选择器上不能正常工作
demo
演示
Edit
编辑
I found out that when you have horizontal scrollbar that causes vertical scrollbar to appear, this function does not work....
我发现当你有水平滚动条导致垂直滚动条出现时,这个功能不起作用......
I found out another solution... use clientHeight
我找到了另一个解决方案......使用 clientHeight
return this.get(0).scrollHeight > this.get(0).clientHeight;
回答by Sean Zheng
Maybe a more simple solution.
也许一个更简单的解决方案。
if ($(document).height() > $(window).height()) {
// scrollbar
}
回答by kpull1
I should change a little thing of what Reigel said:
我应该对 Reigel 所说的做一点改动:
(function($) {
$.fn.hasScrollBar = function() {
return this[0] ? this[0].scrollHeight > this.innerHeight() : false;
}
})(jQuery);
innerHeight counts control's height and its top and bottom paddings
innerHeight 计算控件的高度及其顶部和底部填充
回答by Ajedi32
You can do this using a combination of the Element.scrollHeight
and Element.clientHeight
attributes.
您可以使用Element.scrollHeight
和Element.clientHeight
属性的组合来执行此操作。
According to MDN:
根据 MDN:
The Element.scrollHeightread-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar.It includes the element padding but not its margin.
所述Element.scrollHeight只读属性是一个元素的内容的高度的测量,包括由于溢出内容在屏幕上不可见的。scrollHeight 值等于元素需要的最小 clientHeight,以便在不使用垂直滚动条的情况下适应视点中的所有内容。它包括元素填充但不包括它的边距。
And:
和:
The Element.clientHeightread-only property returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin.
clientHeight can be calculated as CSS height + CSS padding - height of horizontal scrollbar (if present).
所述Element.clientHeight只读属性返回一个元件的内部高度,以像素,包括填充但不水平滚动条高度,边框或余量。
clientHeight 可以计算为 CSS 高度 + CSS 填充 - 水平滚动条的高度(如果存在)。
Therefore, the element will display a scrollbar if the scroll height is greater than the client height, so the answer to your question is:
因此,如果滚动高度大于客户端高度,元素将显示滚动条,因此您的问题的答案是:
function scrollbarVisible(element) {
return element.scrollHeight > element.clientHeight;
}
回答by the4tress
This expands on @Reigel's answer. It will return an answer for horizontal or vertical scrollbars.
这扩展了@Reigel 的回答。它将返回水平或垂直滚动条的答案。
(function($) {
$.fn.hasScrollBar = function() {
var e = this.get(0);
return {
vertical: e.scrollHeight > e.clientHeight,
horizontal: e.scrollWidth > e.clientWidth
};
}
})(jQuery);
Example:
例子:
element.hasScrollBar() // Returns { vertical: true/false, horizontal: true/false }
element.hasScrollBar().vertical // Returns true/false
element.hasScrollBar().horizontal // Returns true/false
回答by Boldewyn
You need element.scrollHeight. Compare it with $(element).height()
.
你需要element.scrollHeight。将其与$(element).height()
.
回答by thegrandoverseer
I made a new custom :pseudo selector for jQuery to test whether an item has one of the following css properties:
我为 jQuery 制作了一个新的自定义 :pseudo 选择器来测试一个项目是否具有以下 css 属性之一:
- overflow: [scroll|auto]
- overflow-x: [scroll|auto]
- overflow-y: [scroll|auto]
- 溢出:[滚动|自动]
- 溢出-x:[滚动|自动]
- 溢出-y:[滚动|自动]
I wanted to find the closest scrollable parent of another element so I also wrote another little jQuery plugin to find the closest parent with overflow.
我想找到另一个元素的最近的可滚动父元素,所以我还编写了另一个小 jQuery 插件来找到最近的带有溢出的父元素。
This solution probably doesn't perform the best, but it does appear to work. I used it in conjunction with the $.scrollTo plugin. Sometimes I need to know whether an element is inside another scrollable container. In that case I want to scroll the parent scrollable element vs the window.
此解决方案可能效果不佳,但似乎确实有效。我将它与 $.scrollTo 插件结合使用。有时我需要知道一个元素是否在另一个可滚动容器内。在这种情况下,我想滚动父可滚动元素与窗口。
I probably should have wrapped this up in a single plugin and added the psuedo selector as a part of the plugin, as well as exposing a 'closest' method to find the closest (parent) scrollable container.
我可能应该将其封装在一个插件中,并添加伪选择器作为插件的一部分,并公开一个“最接近”的方法来查找最近的(父)可滚动容器。
Anywho....here it is.
任何人....在这里。
$.isScrollable jQuery plugin:
$.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'
);
};
$(':scrollable') jQuery pseudo selector:
$(':scrollable') jQuery 伪选择器:
$.expr[":"].scrollable = function(a) {
var elem = $(a);
return elem.isScrollable();
};
$.scrollableparent() jQuery plugin:
$.scrollableparent() jQuery 插件:
$.fn.scrollableparent = function(){
return $(this).closest(':scrollable') || $(window); //default to $('html') instead?
};
Implementation is pretty simple
实现非常简单
//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();
UPDATE:I found that Robert Koritnik already came up with a much more powerful :scrollable pseudo selector that will identify the scrollable axes and height of scrollable containers, as a part of his $.scrollintoview() jQuery plugin. scrollintoview plugin
更新:我发现 Robert Koritnik 已经提出了一个更强大的 :scrollable 伪选择器,它可以识别可滚动轴和可滚动容器的高度,作为他的 $.scrollintoview() jQuery 插件的一部分。滚动视图插件
Here is his fancy pseudo selector (props):
这是他花哨的伪选择器(道具):
$.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();
}
});
回答by Aaron Hopkins
The first solution above works only in IE The second solution above works only in FF
上述第一个解决方案仅适用于 IE 上述第二个解决方案仅适用于 FF
This combination of both functions works in both browsers:
这两个功能的组合适用于两种浏览器:
//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");
}?
- Wrap in a document ready
- monitorWidth1 : the div where the overflow is set to auto
- mtc : a container div inside monitorWidth1
- AdjustOverflowWidth : a css class applied to the #mtc div when the Scrollbar is active *Use the alert to test cross browser, and then comment out for final production code.
- 准备好文件
- monitorWidth1 : 溢出设置为自动的div
- mtc :monitorWidth1 内的容器 div
- AdjustOverflowWidth : 当滚动条处于活动状态时应用于#mtc div 的 css 类 *使用警报来测试跨浏览器,然后注释掉最终的生产代码。
HTH
HTH
回答by Yair Levy
(scrollWidth/Height - clientWidth/Height) is a good indicator for the presence of a scrollbar, but it will give you a "false positive" answer on many occasions. if you need to be accurate i would suggest using the following function. instead of trying to guess if the element is scrollable - you can scroll it...
(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 ))));
}
#outer1, #outer2, #outer3 {
background-color: pink;
overflow: auto;
float: left;
}
#inner {
width: 150px;
height: 150px;
}
button { margin: 2em 0 0 1em; }
<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>
回答by B T
Ugh everyone's answers on here are incomplete, and lets stop using jquery in SO answers already please. Check jquery's documentation if you want info on jquery.
呃,这里每个人的答案都不完整,请让我们停止在 SO 答案中使用 jquery。如果您需要有关 jquery 的信息,请查看 jquery 的文档。
Here's a generalized pure-javascript function for testing whether or not an element has scrollbars in a complete way:
这是一个通用的纯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"
}