社区精选 | 自定义计数器小技巧!CSS 实现长按点赞累加动画
今天小编为大家带来的是社区作者 XboxYan 的文章,让我们一起来学习自定义计数器小技巧吧。
在某条 APP 中,如果长按点赞,会出现这样花里胡哨的动画,如下:
这个动画有两部分组成,其中这个随机表情的实现可以参考 coco 的这篇文章
比较类似,这里就不重复了,我们这里要实现的是这个不断变化的数字动画,如下演示:
仔细观察,主要有以下几个交互:
鼠标按下有一个向上出现的动画,抬起会慢慢消失 数字不断累加 提示文字在达到某一指定值时自动变化,鼓励!> 加油!! > 太棒了!!!
一、鼠标按下抬起交互
<button class="like">长按点赞</button>
用伪元素来实现提示文案,简单修饰一下。
.like{
position: relative;
}
.like::after{
position: absolute;
bottom: 100%;
width: max-content;
font-size: 2rem;
font-style: italic;
font-weight: bolder;
background-image: linear-gradient(#FFCF02, #FF7352);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
content:'x10';
}
效果如下:

.like::after{
/**/
transform: translateY(100%);
opacity: 0;
visibility: hidden;
transition: .3s;
}
.like:active::after{
visibility: visible;
opacity: 1;
transform: translateY(0);
}

关于这个动画技巧,可以参考我这篇文章 CSS 实现按钮点击动效的套路:https://segmentfault.com/a/1190000041400360
.like::after{
/**/
transform: translateY(100%);
opacity: 0;
visibility: hidden;
transition: .3s .3s, 0s .6s transform; /*默认情况下没有transform*/
}
.like:active::after{
visibility: visible;
opacity: 1;
transform: translateY(0);
transition: .3s;
}

二、数字不断累加
<div>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>...</span>
</div>
.like::after{
/**/
--t:0;
counter-reset: time var(--t);
content: counter(time);
}

@keyframes count {
to {
--t: 999
}
}
.like::after{
/**/
--t:0;
counter-reset: time var(--t);
content: counter(time);
animation: count 100s steps(999) forwards;
}

@property --t {
syntax: '<integer>';
inherits: false;
initial-value: 0;
}

.like::after{
/**/
--t:0;
counter-reset: time var(--t);
content: counter(time);
animation: count 100s steps(999) forwards;
animation-play-state: paused; /*默认暂停*/
}
.like:active::after{
/**/
animation-play-state: running; /*按下运行*/
}

三、提示的阶段变化
0~20:鼓励! 20~50:加油!! 50~:太棒了!!!
@counter-style 鼓励 {
system: cyclic;
symbols: '鼓励!';
range: 1 20;
}

.like::after{
content: counter(time) counter(time, 鼓励);
}

@counter-style 鼓励 {
system: cyclic;
symbols: '鼓励!';
range: 1 20;
fallback: 加油
}
@counter-style 加油 {
system: cyclic;
symbols: '加油!!';
range: 21 50;
fallback: 太棒了
}
@counter-style 太棒了 {
system: cyclic;
symbols: '太棒了!!!';
range: 51 infinite;
}
@counter-style 鼓励 {
system: cyclic;
symbols: '鼓励!';
range: 0 20;
fallback: 加油
}
@counter-style 加油 {
system: cyclic;
symbols: '加油!!';
range: 0 50; /*进入到这个计数器,起点肯定已经超过了20*/
fallback: 太棒了
}
@counter-style 太棒了 {
system: cyclic;
symbols: '太棒了!!!';
}


四、总结一下
鼠标按下和抬起的过渡动画通常是相反的,不过可以通过在按下时设置transition来改变抬起的动画 数字不断累加可以借助@property来实现,它可以让 CSS 变量像颜色一样过渡或者动画 计数器可以让CSS 变量渲染到伪元素上 animation-play-state可以实现按下动画开始,抬起动画暂停的效果 自定义计数器可以让指定计数范围内渲染某一些字符 要实现计数的阶段变化可以用fallback进行回退,可以跳转到另一个计数器 提一下兼容性,Chrome 91+,目前还不太适合外部使用,但可以提前了解


关注公众号:拾黑(shiheibook)了解更多
赞助链接:
关注数据与安全,洞悉企业级服务市场:https://www.ijiandao.com/
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

随时掌握互联网精彩
赞助链接