开发者

Sliding Div to auto height

开发者 https://www.devze.com 2023-01-15 11:01 出处:网络
I have a div that I slide in and out. To do this I just increase th开发者_StackOverflow社区e height by 2px every second until a preset height from a height of 0.

I have a div that I slide in and out. To do this I just increase th开发者_StackOverflow社区e height by 2px every second until a preset height from a height of 0.

Is there anyway to determine the content height of the div as the content is unpredictible height considering the starting properties of the div are display:none and height:0?

Thank you.


The trick is to temporarily show it, measure the height, then hide it again. And if you use visibility: hidden and position: absolute, it won't change the page layout while you do it.

function getElementHeight(el)
{
    var styles = {
        visibility: el.style.visibility,
        height: el.style.height,
        position: el.style.position,
        display: el.style.display
    };
    el.style.visibility = "hidden";
    el.style.height = "auto";
    el.style.position = "absolute";
    el.style.display = "block";
    var height = el.offsetHeight;
    el.style.display = styles.display;
    el.style.position = styles.position;
    el.style.height = styles.height;
    el.style.visibility = styles.visibility;
    return height;
}

If you want to get what the style height should be, you can add these two lines after var height = el.offsetHeight;:

el.style.height = height + "px";
height += (height - el.offsetHeight);
0

精彩评论

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