如何建立 CSS3 關鍵幀動畫?
要在 CSS3 中建立關鍵幀動畫,請定義各個關鍵幀。關鍵幀將控制 CSS3 中的中間動畫步驟。關鍵幀是網頁動畫的規則。動畫屬性與關鍵幀一起使用來控制動畫。讓我們看看語法:
語法
@keyframes animationname {selector {styles;}}
上面,
animationname - 動畫的名稱。
selector - 這是關鍵幀選擇器,即動畫持續時間 %。
styles - 這些是 CSS 樣式屬性
將矩形動畫化為圓形
建立一個矩形並將其動畫化為圓形。動畫持續時間設定為 5 秒。from 和 to 表示動畫從當前樣式更改為新樣式。以下是使用 CSS3 建立關鍵幀動畫的示例:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: rgb(218, 78, 36);
border: 4px solid rgb(0, 0, 0);
position: relative;
animation: circleMove 5s infinite;
}
@keyframes circleMove {
from {
left: 0px;
border-radius: 0px;
}
to {
left: 200px;
border-radius: 50%;
}
}
</style>
</head>
<body>
<h1>CSS3 keyframe example</h1>
<div></div>
</body>
</html>
一個動畫包含多個選擇器
設定了一個包含多個選擇器的動畫。選擇器的 CSS 樣式是 top 屬性。為每個選擇器設定動畫持續時間的百分比。我們建立了一個矩形並對其進行了動畫處理:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 150px;
background: blue;
border: 5px solid red;
position: relative;
animation: myrct 4s infinite;
}
@keyframes myrct {
0% {top: 0px;}
20% {top: 150px;}
40% {top: 80px;}
60% {top: 50px;}
80% {top: 80px;}
100% {top: 150px;}
}
</style>
</head>
<body>
<h1>CSS3 keyframe example</h1>
<p>Check the below animation...</p>
<div></div>
</body>
</html>
一個動畫包含多個選擇器和樣式
不僅可以選擇器,還可以使用關鍵幀每次更改樣式。設定的樣式包括 top、bottom、left 屬性。此外,在動畫的每個步驟中,背景顏色和文字顏色都會頻繁變化:
@keyframes myrct {
0% {top: 0px; left: 10px; background: red; color: black;}
20% {bottom: 150px; left: 20px; background: green; color: white;}
40% {bottom: 80px; left: 50px; background: blue; color: white;}
60% {top: 50px; left: 75px; background: orange; color: white;}
80% {bottom: 80px; left: 50px; background: yellow; color: black;}
100% {bottom: 150px; left: 20px; background: navy; color: white;}
}
示例
讓我們來看一個包含多個選擇器和樣式的示例,以對矩形進行動畫處理:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 150px;
background: blue;
border: 5px solid red;
position: relative;
animation: myrct 4s infinite;
}
@keyframes myrct {
0% {top: 0px; left: 10px; background: red; color: black;}
20% {bottom: 150px; left: 20px; background: green; color: white;}
40% {bottom: 80px; left: 50px; background: blue; color: white;}
60% {top: 50px; left: 75px; background: orange; color: white;}
80% {bottom: 80px; left: 50px; background: yellow; color: black;}
100% {bottom: 150px; left: 20px; background: navy; color: white;}
}
</style>
</head>
<body>
<h1>CSS3 keyframe example</h1>
<p>Check the below animation...</p>
<div>Our rectangle</div>
</body>
</html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP