Jquery get height of auto height element
Is there any way to return the height of an element that is already set to auto? I just get 0 when I call $("#element").height();
Here is the jquery code. The img.height() return 0 ther开发者_运维百科efore the end result is off.
img.css({top: (img.parent().height() - img.height()) /2, left: (img.parent().outerWidth() - img.outerWidth()) / 2});
The HTML looks like this:
<div id="exploreImage" class="virtual-room-large" style="width: 288px; height: auto; top: 185px; left: 89px; ">
I have found a workaround for doing a transition with ease-in AND ease-out. This workaround needs the "jump" of the element:
var elementselector = "#elementtoscroll";
$(elementselector ).css("height", "auto");
var elemheight = $(elementselector).css("height");
$(elementselector).css("height", "0");
$(elementselector).css("height", elemheight);
This way, javascript gets the height - I know it's not a beuatiful way, but it works. This is important for example for the ease-out effect.
EDIT: It should be said, that this is just possible with CSS3 and a CSS-Style like this:
#panel{
background-color: #FF00FF;
display: block;
height: 0px;
transition: all 300ms ease-in-out;
overflow: hidden;
}
I had this same problem and found the solution here: http://www.fortwaynewebdevelopment.com/jquery-width-or-height-always-returns-0-fix/
When I'm using jQuery, I like to stick to it as much as I can for consistency's sake.
Actually both solutions - using window.load(){} or $("my element").load(){} worked beautifully for me so I hope this can help you out as well or anyone else finding this issue.
please check you try to get height when DOM is ready, that is to say in the window.onload function.
In case your div element is empty and height is auto, it will return 0. So your div is likely to be empty before full page is loaded.
For example : I want to remember initial heights for my .elementDiv divs :
var initialHeight = [];
window.onload = function() {
$('.elementDiv').each(function(i) {
initialHeight[i]=$(this).height();
});
// then use it
}
When not in the onload function, the heights I get are all 0.
I hope this was the reason, because I don't see anything else..
You can try Window.getComputedStyle();
It will return the a set of computed style, (if ever the style property is not defined e.g. auto)
var elem1 = document.getElementById("elemId");
var style = window.getComputedStyle(elem1);
You can then say
var computedHeight = style.height;
for more info: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
I think offsetHeight or clientHeight or scrollHeight can solve it. for example:
img.parent()[0].offsetHeight
or
img.parent()[0].scrollHeight
Different between these 3 methods can see here:
- http://jsfiddle.net/shibualexis/yVhgM/3/
- What is offsetHeight, clientHeight, scrollHeight?
Did you try $("#element").outerHeight()
? It gets the computed height rather than the explicitly set height.
精彩评论