开发者

Is there a way to find out if an element has a scrollbar on it using JQuery?

Let say I have an element like so

<div id="m开发者_如何学运维yDiv" style="height:10px; width:100px; overflow:scroll;"> 
   random amount of lorem ipsum... 
</div>

Is there a way in JS or Jquery to look at $("#myDiv") and see if it has scrollbars?

Thanks

Dave


This should work

$.fn.hasVerticalScrollBar = function () {
     return this[0].clientHeight < this[0].scrollHeight;
}

$.fn.hasHorizontalScrollBar = function () {
    return this[0].clientWidth < this[0].scrollWidth;
} 

Usage

alert($('#mydivid').hasHorizontalScrollBar());
alert($('#mydivid').hasVerticalScrollBar());

EDIT:

To use this method with invisible element, clone the div, set its opacity to 0, append the clone to the body, check if the clone has the scroll bar and then remove the clone:

var clone = $('#mydivid').clone();
clone.css('opacity', '0').appendTo('body');
if (clone.hasHorizontalScrollBar()) {
   //do the job here
}
clone.remove();


You could wrap the text in another div, and compare the width/height of that one with #myDiv. If it's taller, there is a scrollbar:

<div id="myDiv" style="..."> 
    <div id="inner">random amount of lorem ipsum...</div>
</div>

Example:

if( $('#inner').height() > $('#myDiv').height() ){
  alert('vertical scrollbar');
}

if( $('#inner').width() > $('#myDiv').width() ){
  alert('horizontal scrollbar');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜