检查 HTML 元素是否有滚动条 [英] Check whether HTML element has scrollbars
问题描述
检查元素是否有滚动条的最快方法是什么?
What's the fastest way of checking whether an element has scroll bars?
当然有一件事是检查元素是否大于其视口,这可以通过检查这两个值轻松完成:
One thing of course is checking whether element is larger than its viewport, which can easily be done by checking these two values:
el.scrollHeight > el.offsetHeight || el.scrollWidth > el.offsetWidth
但这并不意味着它也有滚动条(所以它实际上可以被人类滚动).
but that doesn't mean that it has scrollbars as well (so it can actually be scrolled by humans).
如何仅在 1 跨浏览器和 2 javascript(如无 jQuery)中检查滚动条?
How do I check for scrollbars in a 1 cross browser and 2 javascript only (as in no jQuery) way?
仅 Javascript,因为我需要尽可能小的开销,因为我想编写一个非常快的 jQuery 选择器过滤器
Javascript only, because I need as small overhead as possible, because I'd like to write a very fast jQuery selector filter
// check for specific scrollbars
$(":scrollable(x/y/both)")
// check for ANY scrollbar
$(":scrollable")
我想我必须检查 overflow
样式设置,但如何以跨浏览器的方式执行此操作?
I suppose I'd have to check for overflow
style settings but how do I do that in a cross browser way?
不仅是overflow
样式设置.检查元素是否有滚动条并不像看起来那么简单.当元素没有边框时,我上面写的第一个公式可以正常工作,但是当它有时(尤其是当边框具有相当大的宽度时),offset
尺寸可能大于 scroll
维度,但元素仍然可以滚动.我们实际上必须从 offset
维度中减去边框以获得元素的实际可滚动视口,并将其与 scroll
维度进行比较.
Not only overflow
style settings. Checking whether an element has a scrollbar isn't as trivial as it seems. The first formula I've written above works fine when element doesn't have a border, but when it does (especially when border is of considerable width), offset
dimension can be larger than scroll
dimension but the element can still be scrollable. We actually have to subtract borders from offset
dimension to get the actual scrollable viewport of the element and compare that to scroll
dimension.
:scrollable
jQuery 选择器过滤器包含在我的 .scrollintoview()
jQuery 插件中.完整代码可以在我的博客文章 如果有人需要的话.即使它没有提供实际的解决方案 Soumya 的代码也大大帮助我解决了问题.它为我指明了正确的方向.
:scrollable
jQuery selector filter is included in my .scrollintoview()
jQuery plugin. Complete code can be found in my blog post if anybody needs it. Even though it didn't provide the actual solution Soumya's code considerably helped me solve the problem. It pointed me in the right direction.
推荐答案
我几周前在某个地方发现了这个.它对我有用.
I found this somewhere a couple of weeks ago. It worked for me.
var div = document.getElementById('container_div_id');
var hasHorizontalScrollbar = div.scrollWidth > div.clientWidth;
var hasVerticalScrollbar = div.scrollHeight > div.clientHeight;
/* you'll get true/false */
这篇关于检查 HTML 元素是否有滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!