我正在尝试做一个动画,以便在js call 上盒子会立即改变颜色,然后恢复慢慢后,我做到了,但是我想它可能不是最佳解决方案:
var d = $('#d1');
d.click(function() {
d.addClass('high');
setTimeout(function() {
d.addClass('trans');
d.removeClass('high');
setTimeout(function() {
d.removeClass('trans');
}, 1000);
}, 500);
});
div {
width: 100px;
height: 100px;
background: gray;
}
div.high {
background: yellow;
}
.trans {
transition: all 1s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='d1'></div>
<br> click on the box
可以用更少的JS/更最佳解决方案制成吗?
(我正在使用此演示中的单击,但是我需要在JS函数调用上执行此操作(
您可以使用CSS动画简化:
var d = $('#d1');
d.click(function() {
d.addClass('high');
/* No need to remove if you want it to happen one time*/
setTimeout(function() {
d.removeClass('high');
}, 1000);
/**/
});
div {
width: 100px;
height: 100px;
background: gray;
}
div.high {
animation: anim 1s ease-in-out;
}
@keyframes anim {
0%,
50% {
background: yellow;
}
/* We only specify to 50% so it revert back to initial color
and thus can be used with different div having different colors
*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='d1'></div>
click on the box
基于Temani Afif的答案,这是一种使用AnimationEnd事件而不是超时的方法:
:
var d = $('#d1');
d.click(function() {
d.addClass('high');
}).on('animationend', function() {
d.removeClass('high');
});
div {
width: 100px;
height: 100px;
background: gray;
}
div.high {
animation: highlight 1.5s ease-in-out;
}
@keyframes highlight {
0%, 33% {
background: yellow;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='d1'></div>
click on the box
在这里,只有CSS-y方式,但它仅适用于fir单击。就像一个例子一样,没有任何JS,只是为了替代。不要严格,请=(
#d1 {
width: 100px;
height: 100px;
background-color: gray;
}
#d1:focus {
outline: none;
animation: anim 1s ease-in-out;
}
@keyframes anim {
0%,
50% {
background-color: yellow;
}
}
<div id='d1' tabindex='1'></div>
click on the box