【发布时间】:2021-05-15 12:53:59
【问题描述】:
我正在尝试实现一个动画,如果用户点击一个标签,(最初隐藏的)div 将从上到下打开,如果他们再次点击它,div 将从下到上很好地关闭。
/* Firstly I tried using css transitions but it does not work
at all as the entire div just opened without as transition*/
input.trigger+div.mapInfo {
display: none; /* div originally hidden */
height: 0px;
max-height: 0px;
transition: all 300ms;
}
input.trigger:checked+div.mapInfo {
display: block;/*div shown*/
height: auto;
max-height: 500px;
}
/*Then I tried using max-height,min-height, and height for
transitions but it still doesn't work*/
input.trigger + div.mapInfo{
display:none;
min-height:0px;
max-height:0px;
transition:all 300ms;
}
input.trigger:checked + div.mapInfo{
display:block;
min-height:300px;
max-height:500px;
height:auto;
}
/*Hence, I deleted the transition code and tried css
animations now the div opens up nicely but still closed
without animations*/
input.trigger+div.mapInfo {
display: none;
animation: close-up 300ms linear forwards;/*this line of code appears to be not working*/
}
input.trigger:checked+div.mapInfo {
display: block;
animation: open-up 300ms linear forwards;
}
@keyframes close-up {
0% {
max-height: 500px;
}
100% {
max-height: 0px;
}
}
@keyframes open-up {
0% {
max-height: 0px;
}
100% {
max-height: 500px;
}
}
/* Further more I tried using transform:scaleY() and
replacing the max-height, but closing the div still has no animations */
@keyframes close-up{
0%{
transform:scaleY(1)
}
100%{
transform:scaleY(0);
}
}
@keyframes open-up{
0%{
transform:scaleY(0);
}
100%{
transform:scaleY(1);
}
}
<!-- the label that user clicks on -->
<label id="marker6" class="battleMarkers" for="trigger6"><img src="ss_marker.png" alt="" /></label>
<input class="trigger" type="checkbox" id="trigger6">
<!-- the div to be opened-->
<div class="mapInfo" id="info6">
<h2>Sword Beach</h2>
<p>Sword was the easternmost landing site of the Normandy Invasion. Sword was divided into several sectors with each sector divided into beaches. Sword is located about 9 miles from Caen, the goal of the 3rd Infantry Division.</p>
<p>The Sword landing suffered few casualties but it's route inland suffered from traffic congestion that limited the invasion's effectiveness. Troops at Sword experienced the only armour counter-attack of D-Day, mounted by the 21st Panzer Division.</p>
</div>
注意:这个问题与 `this one 不同,因为他/她的 div 的起始高度为 10px,而我的从一开始就隐藏。
【问题讨论】:
-
您介意使用 JS 还是打算使用 CSS?
-
@jacc_01 JS 是不是很困难/令人困惑?现在我知道了一些 js 基础知识,比如变量数据类型循环、函数
-
我注意到你的问题是让 div 从上到下打开,但你尝试的代码是从下到上打开的。从上到下要容易得多,并且提供的两个答案都可以让您做到这一点。如果您确实想要从下到上,那么您将需要 JavaScript。
标签: css css-selectors css-animations