Get visible height of an element instead of its ac

2019-06-17 08:25发布

问题:

This post is related to this one. Please consider reading it as well. :-)

In the post I linked to, I figured the solution to my problem would be to change the target of a link if the visible height of a div is greater than that of another div. In my layout, all the divs I'm referring to have a height of 1100px. But that's not what I want to get. I'd like the script to get height of the div that is currently visible to the visitor, not its real height. Is there a way to do it using jQuery?

Thanks in advance!

回答1:

What you can do is take the elements position to the top of its parent container and then minus it from the parents container height. That will give you the visible height of the element.

$('#container').height() - $('#overflow').position().top

Here is a fiddle showing this.



回答2:

Wrap the contents of the viewport DIV with another DIV. Target that DIV to read the height of all the contents as such:

JQuery: $('div#contents').height();

Layout:

<div id="viewport">
  <div id="contents">...all your div contents...</div>
</div>

Hope this helps. Good Luck.



回答3:

Do you have to use a fixed 1100px height? Cause you could also specify a max-height:1100px; and a height:100%; Depending on what you want to put inside the div you can of course get the current height by

$('.divclass').height();