持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天,点击查看活动详情
最近看到很多按钮加边流动效果,今天我们一起来实现一下。
按钮
带有光变流动的按钮🔘。
结构
因为按钮不仅有视觉效果,还会有文字提示,这里用到了自定义标签text
,当然你也可以用其他的标签或者不用标签包裹也行。
<div class="button">
<span style="--i:0"></span>
<span style="--i:1"></span>
<span style="--i:2"></span>
<span style="--i:3"></span>
<text>也笑</text>
</div>
样式
首先,要给按钮一个基础样式,并给它一个hover
效果,如下:
.button {
width: 10rem;
height: 10rem;
text-align: center;
line-height: 10rem;
color: #fff;
font-size: 2rem;
background-color: rgba(255, 255, 255, .1);
cursor: pointer;
position: relative;
--color: cyan;
}
.button:hover {
background-color: var(--color);
box-shadow: 0 0 1rem var(--color),
0 0 2rem var(--color),
0 0 5rem var(--color);
}
然后,我们需要给边一个统一样式,如下:
.button span {
position: absolute;
display: inline-block;
animation-delay: calc(var(--i) * 0.5s) !important;
}
最后呢,我们需要给每个边特定的样式以及给它们相应的动画,如下:
.button span:nth-child(1),
.button span:nth-child(3) {
width: 100%;
height: 0.3rem;
background: linear-gradient(to right, transparent, var(--color));
border-radius: 0 0.3rem 0.3rem 0;
animation: _animateMove1 2s linear infinite;
left: var(--left);
}
.button span:nth-child(1) {
top: 0;
--left: -100%;
}
.button span:nth-child(3) {
bottom: 0;
--left: 100%;
transform: rotate(180deg);
}
.button span:nth-child(2),
.button span:nth-child(4) {
width: 0.3rem;
height: 100%;
background: linear-gradient(to bottom, transparent, var(--color));
border-radius: 0 0 0.3rem 0.3rem;
animation: _animateMove2 2s linear infinite;
top: var(--top);
}
.button span:nth-child(2) {
right: 0;
--top: -100%;
}
.button span:nth-child(4) {
left: 0;
--top: 100%;
transform: rotate(180deg);
}
效果
效果及代码详情如下:
总结
上与下、左与右其实很相近,样式只需要旋转就可以实现。
在这里,我使用了CSS3 变量的特性,这样的话我们就可以少写一些动画,复用性更高一点。那么问题来了,这个效果还有没有其他实现的方式,答案是肯定的,那么我们可以去掉span
标签,只使用div
的伪元素可以实现吗,小伙伴们可以试一下。