我有一个按钮,当我单击它时,一个div出现并带有关键帧动画。 但是,当我们再单击一次以“关闭”该div时,我希望具有相同的动画(不透明度和高度)。
$('button').click(function() {
if ($(this).hasClass("clicked")) {
$('div').removeClass('In');
$("div").css({ "visibility": "hidden" });
$(this).text("Open ↓");
$(this).removeClass("clicked");
} else {
$('div').addClass('In');
$("div").css({ "visibility": "visible" });
$(this).text("Close ↑");
$(this).addClass("clicked");
}
});
body {
text - align: center
}
div {
display: inline - block;
background: pink;
height: 300 px;
width: 300 px;
visibility: hidden;
}
button {
font - size: 16 px;
}
@keyframes In {
0 % {
opacity: 0;
height: 0
}
100 % {
opacity: 1;
height: 300 px
}
}
.In {
animation - duration: 800 ms;
animation - name: In;
animation - delay: 0 s;
}
<button>Open ↓ </button> <br>
<div> </div>
(也在JSFiddle上)
答案 0 :(得分:1)
我们可以添加另一个类来执行动作。我们可以在类本身中添加不透明度
$('button').click(function() {
var el = $(this);
setTimeout(function() {
if (el.hasClass("clicked")) {
$('div').removeClass('In');
$('div').addClass('Out');
el.text("Open ↓");
el.removeClass("clicked");
} else {
$('div').removeClass('Out');
$('div').addClass('In');
el.text("Close ↑");
el.addClass("clicked");
}
}, 2000); // Will start after 2 seconds
});
body {
text-align: center
}
div {
display: inline-block;
background: pink;
height: 300px;
width: 300px;
opacity: 0;
}
button {
font-size: 16px;
}
@keyframes In {
0% {
opacity: 0;
height: 0
}
100% {
opacity: 1;
height: 300px
}
}
@keyframes Out {
0% {
opacity: 1;
height: 300px
}
100% {
opacity: 0;
height: 0
}
}
.In {
animation-duration: 800ms;
animation-name: In;
animation-delay: 0s;
opacity: 1;
}
.Out {
animation-duration: 800ms;
animation-name: Out;
animation-delay: 0s;
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Open ↓ </button> <br>
<div> </div>