做電商項目時遇到這樣一個需求:點擊商品圖片右上角的收藏按鈕時,按鈕要先放大再回彈,給用戶一個明確的操作反饋。查閱資料後發現,用 CSS3 的 @keyframes 加 animation 就能實現,完全不需要 JS 動畫庫。
CSS3 的 @keyframes 與 animation。JS 只負責在點擊時「加類名」,動畫本身交給 CSS。
<!DOCTYPE html>
<head>
<style type="text/css">
@keyframes myfirst {
0% {
width: 50px;
height: 50px;
top: 10px;
right: 10px;
}
75% {
width: 60px;
height: 60px;
top: 5px;
right: 5px;
}
100% {
width: 50px;
height: 50px;
top: 10px;
right: 10px;
}
}
.warp {
width: 400px;
height: 300px;
position: relative;
background: #ccc;
}
.btn {
position: absolute;
width: 50px;
height: 50px;
border: solid 3px #cc3c24;
top: 10px;
right: 10px;
border-radius: 8px;
cursor: pointer;
}
/* 動畫類,動畫結束後由 JS 移除 */
.btn.cur{
animation: myfirst 0.2s;
}
/* 已收藏狀態 */
.btn.yes{
background: #cc3c24;
}
</style>
</head>
<body>
<div class="warp">
<div class="btn"></div>
</div>
<script src="https://liuxiaofan.com/demo/js/jquery-2.1.4.min.js"></script>
<script>
var btn = $('.btn');
btn.click(function () {
if( $(this).is('.yes') ){
$(this).removeClass('yes');
$(this).removeClass('cur');
}else{
$(this).addClass('yes');
$(this).addClass('cur');
}
});
/* 動畫結束後移除 cur 類,保證下次點擊能重新觸發動畫 */
btn.on('webkitAnimationEnd', function () {
$(this).removeClass('cur');
});
</script>
</body>
</html>


整個交互分兩條線:
狀態線:.yes 類控制按鈕的填充色,切換它就切換了「已收藏 / 未收藏」的外觀。
動畫線:.cur 類承載 animation。點擊時加上它,按鈕在 0.2 秒內經歷「放大到 60px → 回落到 50px」的過程,形成回彈手感。
最關鍵的一步是 webkitAnimationEnd 事件中移除 .cur 類。如果不移除,第二次點擊時類名已經存在,animation 不會重新觸發,動畫就失效了。這是 CSS 動畫反覆播放時最常見的坑。
示例同時改變了 width、height、top、right 四個屬性,這會觸發元素的重排(reflow),性能並不理想。更推薦的做法是只動畫 transform: scale(),它僅在合成層完成,開銷極小:
@keyframes pop {
0% { transform: scale(1); }
75% { transform: scale(1.2); }
100%{ transform: scale(1); }
}
.btn.cur{
animation: pop 0.2s ease-out;
}
另外,webkitAnimationEnd 帶有私有前綴,正式環境中建議同時監聽 animationend,或者用更簡潔的方式——直接監聽元素的 animationend 並配合事件委託,避免在多元素場景下重複綁定。