javascript - div 扩展动画 max-height 不起作用。高度始终为 0

标签 javascript html css

我正在尝试在弹出的 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>

我引用了以下链接。 Expand div on click with smooth animation , How can I transition height: 0; to height: auto; using CSS? .

感谢您的帮助。 :)

最佳答案

不要使用 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/

关于javascript - div 扩展动画 max-height 不起作用。高度始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60035537/

相关文章:

javascript - SharePoint 2013 日历 getSelector 在 IE 中未定义

javascript - 仅从 slickgrid 的标题行隐藏复选框

html - 将我的提交按钮转换为链接并保持相同的样式

javascript - 打开 Chrome 控制台会阻止 Javascript

javascript - 如何正确使用按钮切换功能

html - tablerows 悬停在表格中,偶数/奇数通过 CSS 设置样式

javascript - 无法在 ion-spinner 上执行 ng-click 事件

html - 我有这样的代码需要为更大的屏幕应用媒体查询

html - 当内容增加时,我的内容 div 放错了位置

javascript - 使用溢出时 div 内容向上滚动 : auto in IE 10