javascript - 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?.
谢谢你的帮助。:)
解决方案
不要使用 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
}
推荐阅读
- nginx - 当发送的消息过多时,具有实时消息传递功能的 Web 应用程序会挂起
- ios - Auto hidden keyboard after enter six characters
- javascript - How to expire div on specific day?
- c# - Linq to Sql DataContext 线程安全
- ruby - 正则表达式捕获组不包括
- bash - 从 bash 和 python 访问 ~/.ssh/config 别名
- ruby-on-rails - ransack rails:不适用于使用 *_in 匹配器的空值
- javascript - 如何在ajax调用中获得迭代ID的结果
- colors - Scilab colorbar - 拳头和最后一个颜色更小
- java - 在单例类中添加两个整数值