<分区>
标签 javascript html css
<分区>
我有一个 ul
并点击其中一个 li
我想隐藏其中的子 ul
具有滑动效果。我已经尝试将 animation
的 height
从 100% 调整到 0。但这不起作用。
这是代码片段,在真实场景中会有动态数据和 n 个 li
function hide() {
var li = document.getElementById("game");
game.classList.add("hide")
}
.hide {
height: 0;
overflow: hidden;
animation-name: example;
animation-duration: 4s;
}
@keyframes example {
0% {
height: 100%;
}
25% {
height: 75%;
}
50% {
height: 50%;
}
100% {
height: 0%;
}
}
<ul>
<li>A</li>
<li onclick="hide()">b</li>
<li id="game" style="height:100%">
<ul>
<li>1</li>
<li>2</li>
</ul>
</li>
</ul>
我怎样才能做到这一点?
最佳答案
使用百分比在您的示例中不起作用。
解决方案 1:您需要在 @keyframes
中设置固定高度像这样:
function hide() {
var li = document.getElementById("game");
game.classList.add("hide")
}
.hide {
height: 0;
overflow: hidden;
animation-name: example;
animation-duration: 1s;
}
@keyframes example {
0% {
height: 40px;
}
25% {
height: 30px;
}
50% {
height: 20px;
}
100% {
height: 0px;
}
}
<ul>
<li>A</li>
<li onclick="hide()">b</li>
<li id="game">
<ul>
<li>1</li>
<li>2</li>
</ul>
</li>
</ul>
解决方案 2:向父级添加固定高度 <ul>
元素,然后您可以在 @keyframe
中使用百分比就像这样:
function hide() {
var li = document.getElementById("game");
game.classList.add("hide")
}
.hide {
height: 0;
overflow: hidden;
animation-name: example;
animation-duration: 1s;
}
ul {
height: 200px;
}
@keyframes example {
0% {
height: 100%;
}
25% {
height: 75%;
}
50% {
height: 50%;
}
100% {
height: 0%;
}
}
<ul>
<li>A</li>
<li onclick="hide()">b</li>
<li id="game">
<ul>
<li>1</li>
<li>2</li>
</ul>
</li>
</ul>
Here is an article详细介绍了这个主题。
关于javascript - 如何在css中隐藏带有滑动效果的li,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581969/