線上效果:https://hovertree.com/texiao/css3/37/
透過 @keyframes 規則可以建立動畫,原理是把一套 CSS 樣式「逐漸變化」為另一套樣式,過程中還能多次改變樣式。時間點以百分比表示,也可以用關鍵字 from 與 to,分別等價於 0% 與 100%。0% 是動畫的起點,100% 是終點。為了取得最佳的瀏覽器相容性,建議 ALWAYS 明確定義 0% 與 100% 這兩個選擇器。
語法:
@keyframes animationname {
keyframes-selector { css-styles; }
}
其中 animationname 為必填,用來定義動畫名稱;keyframes-selector 為必填,代表動畫進度的百分比,合法值為 0-100%、from(同 0%)或 to(同 100%);css-styles 亦為必填,是一或多個合法的 CSS 樣式屬性。
注意:動畫建立後,還必須用 animation 相關屬性控制它的外觀,並將動畫與選擇器綁定,才會真正跑起來。
@keyframes hovertreemove {
from { top: 30px; }
to { top: 130px; }
}
效果展示:https://hovertree.com/texiao/css3/37/1.htm
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>css3 使用 animation 與 @keyframes 製作動畫</title>
<style>
@keyframes hovertreemove {
from { top: 30px; }
to { top: 130px; }
}
#hovertreekf {
width: 80px;
height: 80px;
border: 1px solid red;
position: absolute;
background: url(https://hovertree.com/themes/hvtimages/smile.png) no-repeat center;
animation: hovertreemove /* 動畫名稱 */
1s /* 動畫時間 */
linear /* 線性運動 */
infinite /* 無限播放 */
alternate; /* 往返播放 */
}
</style>
</head>
<body>
<div id="hovertreekf"></div>
</body>
</html>
擴散效果的核心手法是:讓一個圓圈用 transform: scale() 從小放大,同時把 opacity 從 0 升到峰值再降回 0,營造出「由中心向外一圈圈蕩漾開來」的視覺。實作時會準備兩組 keyframes(warn 與 warn1),讓兩個圓圈的縮放節奏錯開,看起來就更像連續的波紋。中央則放一個尺寸固定的小圓點作為不動的錨點。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>純 css3 圓形從中心向四周擴散動畫效果</title>
<style>
@keyframes warn {
0% { transform: scale(0.3); opacity: 0.0; }
25% { transform: scale(0.3); opacity: 0.1; }
50% { transform: scale(0.5); opacity: 0.3; }
75% { transform: scale(0.8); opacity: 0.5; }
100% { transform: scale(1); opacity: 0.0; }
}
@keyframes warn1 {
0% { transform: scale(0.3); opacity: 0.0; }
25% { transform: scale(0.3); opacity: 0.1; }
50% { transform: scale(0.3); opacity: 0.3; }
75% { transform: scale(0.5); opacity: 0.5; }
100% { transform: scale(0.8); opacity: 0.0; }
}
.container {
position: relative;
width: 40px;
height: 40px;
}
/* 保持大小不變的小圓圈 */
.dot {
position: absolute;
width: 92px;
height: 92px;
left: 120px;
top: 120px;
border: 2px solid red;
border-radius: 50%;
z-index: 2;
}
/* 向外擴散變大的圓圈 */
.pulse, .pulse1 {
position: absolute;
width: 320px;
height: 320px;
left: 2px;
top: 2px;
border: 6px solid red;
border-radius: 50%;
z-index: 1;
opacity: 0;
animation-iteration-count: infinite;
box-shadow: 1px 1px 30px red;
}
.pulse { animation: warn 2s ease-out infinite; }
.pulse1 { animation: warn1 2s ease-out infinite; }
</style>
</head>
<body>
<div class="container">
<div class="dot"></div>
<div class="pulse"></div>
<div class="pulse1"></div>
</div>
</body>
</html>
參考資料:
實務上,這類動畫常用於推送通知的提示鈴、直播提醒或訊息未讀提示。若使用時想加上瀏覽器前綴,記得補上 -webkit- 與 -moz- 版本以照顧舊版瀏覽器。