我正在制作一个下拉菜单,单击该菜单应会滑入视图。我想让它再次滑回去,但一直在努力寻找方法。我在网上找到的大多数答案都涉及jQuery,但我希望使用Vanilla js来实现。
我的CSS:
.post-more-dropdown {
background-color: #f8f9fa;
display: block;
position: absolute;
right: 0px;
top: 60px;
min-width: 80px;
animation-name: dropdown;
animation-play-state: paused;
animation-fill-mode: backwards;
animation-duration: 0.7s;
a {
display: block;
padding-left: 10px;
padding-top: 10px;
}
a:hover {
background-color: #555555;
color: white;
cursor: pointer;
}
}
@keyframes dropdown {
0% {
max-height: 0px;
opacity: 0;
}
100% {
max-height: 200px;
opacity: 1;
}
}
我的JavaScript:
function post_more_dropdown(post_id) {
dropdown = document.querySelector(`#post-more-dropdown-${post_id}`);
dropdown.style.animationPlayState = "running";
}
这非常适合使下拉菜单在点击时运行,但是我正在努力弄清楚如何在第二次点击时将其撤消。我当时以为我可以创建一个新的@keyframes下拉反向动画并将其添加到类中,但是后来我意识到我无法使用JS在一个类下控制两个动画。我当时想我还可以创建两个不同的类,并使用JS添加/删除这些类以及控制两个不同的动画,但是我觉得我必须要缺少一个更优雅的解决方案。
我觉得animation-direction
将成为答案的一部分,但我还没有弄清楚它如何解决这个问题。
答案 0 :(得分:1)
使用以下CSS,使用JavaScript更改类。
function post_more_dropdown(post_id) {
dropdown = document.querySelector(`#post-more-dropdown-${post_id}`);
if (dropdown.classList.contains('dropdown-animate-forward')) {
dropdown.classList.add('dropdown-animate-backward');
dropdown.classList.remove('dropdown-animate-forward');
} else {
dropdown.classList.add('dropdown-animate-forward');
dropdown.classList.remove('dropdown-animate-backward');
}
}
setInterval(function() {
post_more_dropdown(1)
}, 1000);
.post-more-dropdown {
background-color: #f8f9fa;
display: block;
position: absolute;
right: 0px;
top: 60px;
min-width: 80px;
a {
display: block;
padding-left: 10px;
padding-top: 10px;
}
a:hover {
background-color: #555555;
color: white;
cursor: pointer;
}
}
/* forward animation */
.dropdown-animate-forward {
animation-name: dropdownForward;
animation-fill-mode: backwards;
animation-duration: 0.7s;
}
@keyframes dropdownForward {
0% {
max-height: 0px;
opacity: 0;
}
100% {
max-height: 200px;
opacity: 1;
}
}
/* backward animation */
.dropdown-animate-backward {
animation-name: dropdownBackward;
animation-fill-mode: forward;
animation-duration: 0.7s;
}
@keyframes dropdownBackward {
0% {
max-height: 200px;
opacity: 1;
}
100% {
max-height: 0px;
opacity: 0;
}
}
<div id="post-more-dropdown-1" class="post-more-dropdown">Post more</div>