CSS动画输出后动画输入

  • 本文关键字:动画 输出 CSS html css
  • 更新时间 :
  • 英文 :


it is displayed时,我已经在HTML元素的属性中设置了动画,当单击按钮it should hide with same animation时,我希望反向播放相同的动画。我怎样才能做到这一点。

";"动画";正在工作:

.modal{
animation: myAnim 1s ease 0s 1 normal forwards;
}
@keyframes  myAnim {
0% {
opacity: 0;
transform: translateX(-50px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}

HTML:

<div id="myModal"  class="modal fixed hidden z-1 w-full h-full bg-red-100 h-screen ">
<button  id="myBtn" class=" p-2 bg-yellow-400 rounded m-4 absolute right-0  text-xs font-bold ">
HIDE/SHOW..
</button>

我正在使用JS显示/隐藏模态。如何使用相同的动画隐藏模态。

创建两个类,一个用于使模态出现,另一个用于让它消失,

出现的类别

.modal-appr{
animation: appr 1s ease 0s 1 normal forwards;
}
@keyframes  appr {
0% {
opacity: 0;
transform: translateX(-50px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}

类以使模态消失

.modal-disappr{
animation: disappr 1s ease 0s 1 normal forwards;
}
@keyframes  disappr {
0% {
opacity: 1;
transform: translateX(0);
}
100% {
opacity: 0;
transform: translateX(-50px);
}
}

现在,当按钮切换时,只需使用Javascript将这些类添加到模态的classlist

const btn = document.querySelector('mybtn');
const modal = document.querySelector('#myModal');
btn.addEventListener ('click', function toggleClass () {
if(modal.classList.contains('appr')) {
modal.classList.add('disappr');
modal.classList.remove('appr');
} else {
modal.classList.add('appr');
modal.classList.remove('disappr');
}
})

您可以通过使用toggle类和transition来实现这一点。

let btn = document.getElementById('model_btn');
let model = document.getElementById('model');
btn.addEventListener('click', function(){
model.classList.toggle('show');
})
/* Styling the markup */
#model{
width: 200px;
height: 100px;
background-color: yellow;
padding: 20px;
margin-bottom: 20px;
}
#model_btn{
border: none;
background-color: green;
padding: 10px;
color: white;
cursor: pointer;
}
/* Showing and hiding animation with transition */
#model{
position: relative;
visibility: none;
opacity: 0;
top: 0;
left: 0;
transform: translateX(-50px);
transition: all 1s ease;
}
#model.show{
visibility: visible;
opacity: 1;
transform: translateX(0px);
}
<div id="model">
Content
</div>
<button id="model_btn">Show/Hide Model</button>

动画/关键帧方法。

let btn = document.getElementById('model_btn');
let model = document.getElementById('model');
btn.addEventListener('click', function(){
model.classList.toggle('show');
})
/* Styling the markup */
#model{
width: 200px;
height: 100px;
background-color: yellow;
padding: 20px;
margin-bottom: 20px;
visibility: none;
opacity: 0;
transform: translateX(-50px);
}
#model_btn{
border: none;
background-color: green;
padding: 10px;
color: white;
cursor: pointer;
}
.show{
animation: myAnim 1s ease 0s 1 normal forwards;
}
@keyframes  myAnim {
0% {
visibility: none;
opacity: 0;
transform: translateX(-50px);
}
100% {
visibility: visible;
opacity: 1;
transform: translateX(0);
}
}
<div id="model">
Content
</div>
<button id="model_btn">Show/Hide Model</button>

最新更新