CSS 實(shí)現(xiàn)按鈕點(diǎn)擊動(dòng)效的套路
作者:XboxYan
來源:SegmentFault 思否社區(qū)
在 Web 中,大部分按鈕可能都是平平無奇的,有時(shí)候?yàn)榱藦?qiáng)調(diào)品牌特殊或者滿足特殊功能,可能需要給按鈕添加一點(diǎn)點(diǎn)擊動(dòng)效。比如,用過 Ant Design 的小伙伴應(yīng)該都能發(fā)現(xiàn),在點(diǎn)擊按鈕的時(shí)候會有一個(gè)很微妙的水波動(dòng)畫

這就非常有特色了,看到這樣的按鈕自然會聯(lián)系上 Ant Design 。
動(dòng)畫過程其實(shí)不復(fù)雜,看了一下官方的實(shí)現(xiàn),是通過 js 動(dòng)態(tài)更改屬性實(shí)現(xiàn)的,在點(diǎn)擊的時(shí)候,改變屬性,觸發(fā)動(dòng)畫,當(dāng)動(dòng)畫結(jié)束之后,再將該屬性還原(還原是為了保證下次點(diǎn)擊仍然有動(dòng)畫),如下

看著好像有點(diǎn)麻煩?其實(shí),這種效果也是可以純 CSS 實(shí)現(xiàn)的,而且還能實(shí)現(xiàn)其他更多有趣的效果

一起看看吧~
一、CSS 過渡動(dòng)畫
通常 CSS 中實(shí)現(xiàn)動(dòng)畫有兩種思路,transition和animation。一般而言,簡單的、需要主動(dòng)觸發(fā)(:hover 、:active或者動(dòng)態(tài)切換類名等)的可以用transition實(shí)現(xiàn),其他的都可以用animation。
回到這個(gè)例子,動(dòng)畫足夠簡單了,就兩個(gè)變化,而且需要主動(dòng)觸發(fā)(這里是點(diǎn)擊,可以想到:active),所以優(yōu)先考慮用transition來實(shí)現(xiàn)。
觀察整個(gè)動(dòng)畫,其實(shí)就是兩個(gè)效果疊加而成
陰影不斷擴(kuò)大 透明度不斷降低
/* 初始狀態(tài) */
button{
opacity: .4;
transition: .3s;
}
/* 擴(kuò)散狀態(tài) */
button{
box-shadow: 0 0 0 6px var(--primary-color);
opacity: 0;
}
二、CSS 點(diǎn)擊動(dòng)畫
<button class="button">Default</button>
:root{
--primary-color: royalblue;
}
.button{
padding: 5px 16px;
color: #000000d9;
border: 1px solid #d9d9d9;
background-color: transparent;
border-radius: 2px;
line-height: 1.4;
box-shadow: 0 2px #00000004;
cursor: pointer;
transition: .3s;
}
.button:hover{
color: var(--primary-color);
border-color: currentColor;
}
.button::after{
content: '';
position: absolute;
inset: 0;
border-radius: inherit;
opacity: 0.4;
transition: .3s;
}
.button:active::after{
box-shadow: 0 0 0 6px var(--primary-color);
opacity: 0;
}

三、CSS 過渡重置

.button::after{
/*其他樣式*/
opacity: 0;
box-shadow: 0 0 0 6px var(--primary-color);
transition: .3s;
}
/*點(diǎn)擊*/
.button:active::after{
box-shadow: none;
opacity: 0.4;
transition: 0s; /*取消過渡*/
}

四、其他動(dòng)效案例

.icon{
transform: rotate(360deg);
transition: .5s;
}
.button:active .icon{
transform: rotate(0);
transition: 0s;
}


五、更復(fù)雜的動(dòng)畫

@keyframes tada {
from {
transform: scale3d(1, 1, 1)
}
10%, 20% {
transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg)
}
30%, 50%, 70%, 90% {
transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg)
}
40%, 60%, 80% {
transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg)
}
to {
transform: scale3d(1, 1, 1)
}
}
.button{
animation: tada 1s;
}
.button:active{
animation: none;
}

.button{
animation: jump 0s;
}
.button:hover{
animation-duration: 1s;
}
.button:active{
animation: none;
}



六、總結(jié)和說明
簡單動(dòng)畫用transition,其他用 animation
transition 可以通過設(shè)置時(shí)長為 0 來重置
animation 可以通過設(shè)置 none 來重置
在 :active 時(shí)重置動(dòng)畫,點(diǎn)擊后會再次運(yùn)行動(dòng)畫
復(fù)雜的動(dòng)畫可以借助現(xiàn)有的動(dòng)畫庫,例如 anmate.css
設(shè)置動(dòng)畫時(shí)長為 0 可以避免首次渲染出現(xiàn)動(dòng)畫

