js实现每次点击都重复执行CSS动画——animation

Write By Monkeyfly

以下内容均为原创,如需转载请注明出处。

前提

想实现的效果:每次点击span元素时,都要实现样式的过渡变换并最终恢复默认样式(主要指背景颜色和字体颜色)
具体变化过程:默认颜色——指定颜色——恢复默认颜色

最终效果如下图示:

这里写图片描述

成功的做法

该做法的出处:javascript中animation运动, 怎样通过点击事件让他重复执行

注:这一做法是在segmentfault的评论中发现的。(因为评论默认隐藏,点击才能查看,所以之前并没有看过评论)

使用animationend事件将动画(animation)属性去掉,下次点击再加上。

CSS 动画播放时,会发生以下三个事件:

animationstart // CSS 动画开始后触发
animationiteration //CSS 动画重复播放时触发
animationend // CSS 动画完成后触发

所以,只要在动画完成后,将动画属性清除掉就可以实现了。

点击查看详情:animationend 事件

具体代码如下所示:

//CSS样式:
span.msg-data{
    display: inline-block;
    width: 3.6rem;
    height: 0.67rem;
    line-height: 0.67rem;
    margin-bottom:0.4rem;
    margin-left: 0.47rem;
    background-color: #fff;
    border-radius: 0.05rem;
    border:0.02rem solid #e5e5e5;
    text-align: center;
    font-size: 0.32rem;
    color:#acacac;
}
//自定义动画效果
@keyframes switchColor{
    0%  {background-color:#fff;color:#acacac;}
    50% {background-color:#ff9900;color:#fff;}
    100%{background-color:#fff;color:#acacac;}
}
//js代码:
$("span.msg-data").bind("click",function(event) {
    $(this).css('animation', 'switchColor 0.8s');
});
$("span.msg-data").each(function() {
    $(this)[0].addEventListener("animationend",function(){
        $(this).css("animation","");
    });
});

尝试过的错误做法

/*做法1:每次点击前先清除掉动画属性。【实测失败】*/
//js:代码
$("span.msg-data").bind("click",function(event) {
    $(this).css('animation', '');
    $(this).css('animation', 'switchColor 0.8s');
});
/*做法2:把animation的代码放在一个新的类名中,通过添加一个延时器删除类名实现。【实测失败】*/
//css代码:通过动态的添加和删除类名实现
span.selected{
    background-color: #ff9900;
    color:#fefefe;
}
//js:代码
$("span.msg-data").bind("click",function(event) {
    $(this).addClass('selected');
    setTimeout(function () {   
        $(this).removeClass('selected');
    }, 1000); 
});

失败效果的演示图

如下图所示,只有首次点击才有效。

这里写图片描述

  • 19
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值