Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

javascript - jQuery .height() outputting same value as .scrollHeight on div with overflow:auto (IE8)

After routing around many other questions I have not found an answer that fixes my problem.

I am writing a script to find out whether the div is overflowing. But when trying to retrieve the visible height with jQuery.height(), jQuery.innerHeight() or JavaScripts offsetHeight. I am given the value of the whole div (Including the part which is overflowing) i.e: the same value as scrollHeight.

The containing DIVs style:

{
    overflow-x: hidden;
    overflow-y: auto;
    width: 73%;
    bottom: 0px;
    float: left;
    height: 100%;
    top: 0px;
}

I've created a mock up of the scenario on jsFiddle: http://jsfiddle.net/Lukedturnbull/L2bxmszv/3/ (Make sure to make the preview screen smaller to create the scroll bar)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Everything seems fine, jQuery.height() and jQuery.innerHeight() has nothing to do with the overflow property. They will return heights, not just the visible part.

If you want to know the content height you have to use scrollHeight. This scrollHeight is a regular javascript property you don't have to use jQuery

document.getElementById("wrapper").scrollHeight;

Or you can use jQuery selector

$('#wrapper')[0].scrollHeight;

See the working jsfiddle: http://jsfiddle.net/scgz7an5/1/

Notice that

$('#wrapper').scrollHeight;

returns undefined.

UPDATE

You forgot the most important part of floating elements. You forgot to clear them.

Take a look at this jsfiddle, is an edit of yours but with floating elements cleared. There you see different values for scrollHeight and jQuery.height(). See that .structureContent is the one that has the scroll bar, not .content neither .width100.

.structureContent has overflow:auto and the scrollbar you see comes from it.

http://jsfiddle.net/L2bxmszv/5/

I added this class to clear your floating elements.

.clearfix:before,
.clearfix:after, {
  content: '020';
  display: block;
  overflow: hidden;
  visibility: hidden;
  width: 0;
  height: 0; }
.clearfix:after {
  clear: both; }
.clearfix {
  zoom: 1; }

The output was this:

.content
324 for scrollHeight
324 for clientHeight
324 for jQuery.height()
.structureContent
324 for scrollHeight
276 for clientHeight
276 for jQuery.height()

See a great article about floating elements and clearing them here: http://css-tricks.com/all-about-floats/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...