将 Div 滑动到自动高度

发布于 2024-09-18 07:14:53 字数 146 浏览 4 评论 0原文

我有一个可以滑进滑出的 div。 为此,我只需每秒增加 2px 的高度,直到从高度 0 开始达到预设高度。

是否有办法确定 div 的内容高度,因为考虑到 div 的起始属性为 display:none,内容的高度是不可预测的和高度:0?

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮光之海 2024-09-25 07:14:53

诀窍是暂时显示它,测量高度,然后再次隐藏它。如果您使用visibility:hidden和position:absolute,它不会改变页面布局。

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

如果你想获得样式高度应该是多少,可以在 var height = el.offsetHeight; 之后添加这两行:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文