首页 > 解决方案 > div 扩展动画最大高度不起作用。高度始终为 0

问题描述

我正在尝试在弹出 div 元素上制作扩展动画。

我想在打开主页时显示带有扩展动画的弹出 div。

但总是弹出div的高度为0。我尝试了很多方法,但没有任何效果。

无处不在代码下方,控制弹出层的高度。

    .popupLayer     //I tried setting it's height not to 0, but same.
    {
        position:absolute;

        width:76%;

        left:50%;
        top:0%;
        transform: translate(-50%, -55%);

        display:none;
        background-color:white;
        border-radius: 25px;
        overflow: hidden;
    }

    .expand{
        max-height:86%;
        transition: max-height 2s ease-in;
    }

我正在尝试使用以下代码:

window.onload = function(){
    var expandDiv = document.getElementsByClassName('popupLayer')[0];

    expandDiv.style.display='inline';
    expandDiv.style.top = '55%';

    $(expandDiv).addClass('expand');
};

<body>
    ... // some elements including popup div..
    <div class = 'popupLayer'>  
          ...// popuplayer body
    </div>
    ...
</body>

我参考了以下链接。用平滑动画点击展开 div我如何过渡高度:0;到高度:自动;使用 CSS?.

谢谢你的帮助。:)

标签: javascripthtmlcss

解决方案


不要使用 max-height, class 进行动画。直接在CSS和JS中分别设置transition和height:

关键点:

  • 在 CSS 规则中设置初始高度和过渡。
  • 只增加 JS 的高度。添加类不会触发 CSS 动画

JS:

    setTimeout(function() { //setTimeout is to add a delay.
        var expandDiv = document.getElementsByClassName('popupLayer')[0];
        expandDiv.style.display = 'block';
        expandDiv.style.top = '55%';
        setTimeout(function() {
            expandDiv.style.height = '55%'; // This is also for showing the animation.
        }, 1000);
    }, 4000);

CSS:

            .popupLayer {
                 position: absolute;
                 width: 76%;
                 left: 50%;
                 top: 0%;
                 transform: translate(-50%, -55%);
                 outline: 1px solid red;
                 display: none;
                 background-color: white;
                 border-radius: 25px;
                 overflow: hidden;
                 transition: height 4s ease-in;
                 height: 0; // Animation works if you set initial height
             }

演示:https ://jsfiddle.net/lotusgodkk/GCu2D/6016/


推荐阅读