Sliding Div to auto height

自作多情 提交于 2019-12-08 05:38:40

问题


I have a div that I slide in and out. To do this I just increase the 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.


回答1:


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);


来源:https://stackoverflow.com/questions/3688504/sliding-div-to-auto-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!