我有一个移动菜单动画,该动画是通过Javascript(下面的实时代码段中的简化版本)添加了一些CSS类触发的。
我遇到的问题是,尽管菜单会正确设置动画效果,但是当我关闭菜单时,它会消失并且不会像我预期的那样淡出。
我已经在JS中记录了有关不同阶段的功能的注释,但是我似乎无法像CSS动画类所说的那样将其淡出?
任何帮助都会很棒。
CodePen:https://codepen.io/emilychews/pen/bQOXVm
谢谢艾米丽。
var mobileMenuButton = document.querySelector(".button")
var mobileMenu = document.querySelector(".menu")
// TOGGLE MOBILE MENU
var clicked = false
function toggleMobileMenu() {
if (clicked === false) {
// removes the `display-none` class added below in the `else` part of the statement, so menu can be toggled more than once
mobileMenu.classList.remove("display-none")
// changes `display:none` from stylesheet to `display:flex`
mobileMenu.classList.add("display")
// removes inactive animation that is added below
mobileMenu.classList.remove("mobileMenuInactive")
// adds the menuActive animation that animates the menu in
mobileMenu.classList.add("mobileMenuActive")
// changes word on menu button
mobileMenuButton.textContent = "Close"
clicked = true
} else {
mobileMenu.classList.remove("mobileMenuActive")
mobileMenu.classList.add("mobileMenuInactive")
mobileMenuButton.textContent = "Menu"
mobileMenu.classList.add("display-none")
clicked = false
}
}
mobileMenuButton.addEventListener("click", function() {
toggleMobileMenu()
}, false)
body {
margin: 0;
padding: 0;
display: flex;
width: 100%;
height: 100vh;
justify-content: center;
align-items: center;
}
.wrapper {
display: flex;
align-items: center;
}
.menu {
display: none;
align-items: center;
justify-content: center;
min-width: 150px;
background: blue;
right: 0;
top: 6rem;
padding: 10px 0px;
z-index: 99;
width: 20%;
height: calc(100vh - 10rem);
color: white
}
.button {
margin: 0 0 0 3rem;
cursor: pointer;
padding: 10px 20px;
background: gray;
color: white;
}
/*add & remove `display` property*/
.menu.display {display: flex;}
.menu.display-none {display: none;}
/*animations*/
.menu.mobileMenuActive {
animation: showMobileMenu .5s ease-in forwards;
}
.menu.mobileMenuInactive {
animation: removeMobileMenu .5s ease-out forwards;
}
@keyframes showMobileMenu {
0% {opacity: 0;}
100% {opacity: 1;}
}
@keyframes removeMobileMenu {
0% {opacity: 1;}
100% {opacity: 0;}
}
<div class="wrapper">
<div class="menu">Menu</div>
<div class="button">Click Me</div>
</div>
答案 0 :(得分:0)
您需要等待500毫秒(动画的时间),然后再将显示传递给无显示:
setTimeout(function(){
mobileMenu.classList.add("display-none");
},500);