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

您所在的位置:网站首页 css动画animation效果 js实现每次点击都重复执行CSS动画

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

2024-07-17 19:47| 来源: 网络整理| 查看: 265

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); }); 失败效果的演示图

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

这里写图片描述



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3