Detecting presence of a scroll bar in a DIV using jQuery? [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

This question already has an answer here:

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.

Any ideas guys?

回答1:

Assuming overflow on the div is 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; 


回答2:

// 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 */ }  


回答3:

I will revise what bobince mentioned above since you are asking for jQuery

var div= $('#something'); var hasVerticalScrollbar= div[0].scrollHeight > div[0].clientHeight; var hasHorizontalScrollbar= div[0].scrollWidth > div[0].clientWidth; 

This is because scrollHeight and scrollWidth are DOM properties.



回答4:

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 wrapperDiv with the height of containerDiv (which normally has the scroll bar if the content is too large).

If the height of wrapperDiv is bigger than the height of containerDiv then there is a scroll bar, if it is smaller, then there is no scroll bar.

.... content here...


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!