我每次单击按钮时都尝试应用淡入淡出过渡。
实现这一目标的最佳做法是什么?
添加之后,而不是.addClass(),然后是.removeClass(), 想象一下像.apply()那样只会应用一次类 所以它没有"保持"上课。
现在我有.toggleClass
只会在每次点击时应用转换(基本上就像:addClass,removeClass,addClass等)。我可以考虑通过查看它是否已经有类来做另一种方式,如果没有,然后删除它并再次添加它,但它似乎反直觉并且让我认为必须有一种更简单和更清洁的方式这样做。
$("#btn").click(function() {
$("#cat").toggleClass("fade");
})

@import url('https://fonts.googleapis.com/css?family=Yatra+One');
body,
html {
height: 100%;
width: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #eee;
}
.generator {
height: 400px;
width: 400px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
#cat {
height: 300px;
width: 400px;
border-radius: 5px;
transform: scale(1);
opacity: 1;
}
.fade {
animation: fade .5s linear forwards;
}
@keyframes fade {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(0);
opacity: 0;
}
100% {
transform: scale(1);
opacity: 1;
}
}
#btn {
height: 90px;
width: 400px;
outline: none;
border: none;
border-radius: 5px;
background-color: #4682B4;
color: white;
font-size: 1.75em;
font-family: Yatra One;
transition: background-color 0.1s ease-in-out;
}
#btn:hover {
cursor: pointer;
background-color: #508EC3;
}
#btn:active {
background-color: #4293D8;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="generator">
<img id="cat" src="https://i.imgur.com/RVQZ9UM.png" alt="cat" />
<button id="btn">New cat</button>
</div>
</div>
&#13;
答案 0 :(得分:2)
您可以通过收听动画事件来删除动画结束时的fade
课程:
$("#cat").bind('oanimationend animationend webkitAnimationEnd', function() {
$(this).removeClass("fade");
});
在这种情况下,您可以使用addClass
代替toggleClass
。
答案 1 :(得分:0)
在这里使用toogleClass()
可能不是最佳解决方案。会发生什么:
<img>
没有.fade
类但是现在我没有更好的办法。 Nandita的回答实际上与更多代码的行为相同。
阿里的其中一个实际上是最好的一个:
$("#btn").click(function() {
$("#cat").addClass("fade");
})
$("#cat").bind('oanimationend animationend webkitAnimationEnd', function() {
$(this).removeClass("fade");
});
在动画完成时,听取动画事件以删除.fade
类。