我试图通过 display:none
我的假设是 - 创建一个动态居中的 div,它也通过使用过渡动画。 我正在寻找纯 CSS 解决方案。
这是我的方法。
document.querySelector('#one').onclick = function () {
document.querySelector('#two').classList.add("hidden")
}
#content {
transition: all 0.5s ease;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}
#one, #two {
width: 300px;
height: 150px;
line-height: 150px;
text-align: center;
}
#one {
background-color: cyan;
}
#two {
background-color: magenta;
}
.hidden {
display:none;
}
<div id="content" class="centered">
<div id="one">PRESS ME</div>
<div id="two">TO MAKE ME DISAPPEAR</div>
</div>
编辑:在提供的解决方案中不必是display:none
最佳答案
您不能使用 display:none
进行转换,因为转换没有引用点,但您可以使用高度进行转换。此外,您还希望过渡位于您试图隐藏的元素上。然后父 div 将收缩,因为元素不再在其中。像这样:
document.querySelector('#one').onclick = function () {
document.querySelector('#two').classList.add("hidden")
}
.centered {
position: fixed;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}
#one, #two {
width: 300px;
height: 150px;
line-height: 150px;
text-align: center;
}
#one {
background-color: cyan;
}
#two {
background-color: magenta;
transition: all 0.5s ease;
}
#two.hidden {
height:0;
overflow:hidden;
}
<div id="content" class="centered">
<div id="one">PRESS ME</div>
<div id="two">TO MAKE ME DISAPPEAR</div>
</div>
如果您需要将父元素作为需要动画的 div,那么您可以在父 div 上使用高度调整。因此,由于您有 2 个 150px 的 div,因此给您的 #content
div 设置 300px 的高度,然后将该 div 转换为 150px。此外,您可能希望将隐藏类添加到 #content
div,然后给 #two
显示 none。像这样:
document.querySelector('#one').onclick = function () {
document.querySelector('#content').classList.add("hidden")
}
#content {
transition: all 0.5s ease;
border:5px solid #000;
height:300px;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}
#one, #two {
width: 300px;
height: 150px;
line-height: 150px;
text-align: center;
}
#one {
background-color: cyan;
}
#two {
background-color: magenta;
}
#content.hidden {
height:150px;
overflow:hidden;
}
#content.hidden #two{
display:none;
}
<div id="content" class="centered">
<div id="one">PRESS ME</div>
<div id="two">TO MAKE ME DISAPPEAR</div>
</div>
关于html - 仅使用 CSS 的父 div 的动态大小动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684228/