我想延迟关键帧动画的播放时间,但不起作用。 这是一个在单击按钮上具有不透明动画的div。问题在于动画开始前的不透明度为100%。
$('button').click(function() {
if ($(this).hasClass("clicked")) {
$('div').removeClass('In');
$('div').addClass('Out');
$(this).text("Open ↓");
$(this).removeClass("clicked");
} else {
$('div').addClass('In');
$('div').removeClass('Out');
$(this).text("Close ↑");
$(this).addClass("clicked");
}
});
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: 0.3s;
opacity: 1;
}
.Out {
animation-duration: 800ms;
animation-name: Out;
animation-delay: 0.3s;
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Open ↓ </button> <br>
<div> </div>
这里的MY JSFIDDLE有问题。
答案 0 :(得分:2)
使用过渡而不是动画,您还将获得更简单的代码:
$('button').click(function() {
if ($(this).hasClass("clicked")) {
$(this).text("Open ↓");
} else {
$(this).text("Close ↑");
}
$('div.box').toggleClass('In');
$(this).toggleClass("clicked");
});
body {
text-align: center
}
div.box {
display: inline-block;
background: pink;
height: 0;
width: 300px;
opacity: 0;
transition: .8s .3s;
}
button {
font-size: 16px;
}
div.In {
opacity: 1;
height: 300px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Open ↓ </button> <br>
<div class="box"> </div>
考虑到您的代码,您可以像这样更正它:
$('button').click(function() {
if ($(this).hasClass("clicked")) {
$('div').removeClass('In');
$('div').addClass('Out');
$(this).text("Open ↓");
$(this).removeClass("clicked");
} else {
$('div').addClass('In');
$('div').removeClass('Out');
$(this).text("Close ↑");
$(this).addClass("clicked");
}
});
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: 0.3s;
animation-fill-mode:forwards; /*Added this*/
/* opacity:0; removed*/
}
.Out {
animation-duration: 800ms;
animation-name: Out;
animation-delay: 0.3s;
animation-fill-mode:forwards; /*Added this*/
opacity:1;
height:300px; /*Added this*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Open ↓ </button> <br>
<div> </div>