我创建了一个 Angular 侧边栏,我试图用 CSS 动画显示和隐藏它 Online Example :
侧边栏组件依赖于服务来知道何时隐藏和显示:
<div id="sidebar" [ngClass]="{'hide': sidebarService.hidden, 'show': !sidebarService.hidden}">
<button type="button" (click)="sidebarService.toggle()">
Close Sidebar
</button>
<nav>
<ul>
<li>
<a href="#">Page 3</a>
</li>
<li>
<a href="#">Page 4</a>
</li>
</ul>
</nav>
</div>
我使用的 CSS 如下:
@keyframes show {
from {left: -100%;}
to {left: 0;}
}
@keyframes hide {
from {left: 0;}
to {left: -100%;}
}
#sidebar {
background-color: #e0e0e0;
border: 1px solid red;
height: 100%;
overflow-x: hidden;
overflow-y: auto;
position: fixed;
top: 0;
left: -100%;
right: 0;
bottom: 0;
width: 100%;
}
.hide {
animation-name: hide;
animation-duration: 1s;
}
.show {
animation-name: show;
animation-duration: 1s;
}
我发现了两个问题:
1 - 侧边栏最初显示为可见,之后立即关闭;
2 - 单击打开侧边栏时会打开,但完成后它会消失。
我不确定我在这里遗漏了什么......
最佳答案
问题是您设置了关键帧动画隐藏,您在其中设置了 from : 0%
和 to: -100%
。这意味着动画从 0 处的侧边栏开始。
所以它从 -100%(您在 #sidebar 上设置的默认值)开始,转到 0%
的 from
位置,然后转到 到
位置。这就是边栏在加载时出现的原因。
然后显示动画再次隐藏侧边栏,因为您没有设置 animation-fill-mode
,它应该是 forwards
。如果不是,则在任何动画结束时,元素将返回到您在 #sidebar
上设置为 -100%
的默认位置。于是又躲起来了。
(在这种情况下)您可以完全跳过动画,只使用过渡
#sidebar {
background-color: #e0e0e0;
border: 1px solid red;
height: 100%;
overflow-x: hidden;
overflow-y: auto;
position: fixed;
top: 0;
left: -100%;
right: 0;
bottom: 0;
width: 100%;
transition: 1s;
}
#sidebar.hide {
left: -100%;
}
#sidebar.show {
left: 0;
}
关于css - 在组件中使用 CSS 动画显示和隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54235497/