如何使用 CSS 為按鈕新增動畫?
要在網頁上為按鈕新增動畫,請使用 transition 屬性。同時設定過渡動畫的持續時間。使用按鈕上的 :after 選擇器,設定按鈕在被點選之後外觀如何發生改變的動畫。
建立按鈕
首先,使用 <button> 元素建立一個按鈕 −
<button>Click Here</button>
設定按鈕樣式
此處的按鈕具有樣式。將位置設定為 relative,將游標設定為 pointer。此外,還設定寬度 −
button {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
position: relative;
background-color: rgb(100, 0, 84);
border: none;
font-size: 28px;
color: rgb(255, 169, 255);
padding: 20px;
width: 200px;
text-align: center;
box-shadow: 5px 10px 18px rgb(121, 82, 185);
text-decoration: none;
overflow: hidden;
cursor: pointer;
}
為被點選的按鈕新增動畫
transition 屬性用於在按鈕被點選之後立即設定動畫。過渡動畫的持續時間設定為 0.8 秒 −
button:after {
content: "";
background: rgb(251, 255, 0);
display: block;
position: absolute;
padding-top: 300%;
padding-left: 350%;
margin-left: -20px;
margin-top: -120%;
opacity: 0;
transition: all 0.8s
}
設定處於活動狀態的按鈕樣式
:active 選擇器用於在按鈕處於活動狀態時選擇該按鈕並設定其樣式 −
button:active:after {
padding: 0;
margin: 0;
opacity: 1;
transition: 0s
}
示例
以下程式碼是使用 CSS 為按鈕新增動畫 −
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
button {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
position: relative;
background-color: rgb(100, 0, 84);
border: none;
font-size: 28px;
color: rgb(255, 169, 255);
padding: 20px;
width: 200px;
text-align: center;
box-shadow: 5px 10px 18px rgb(121, 82, 185);
text-decoration: none;
overflow: hidden;
cursor: pointer;
}
button:after {
content: "";
background: rgb(251, 255, 0);
display: block;
position: absolute;
padding-top: 300%;
padding-left: 350%;
margin-left: -20px;
margin-top: -120%;
opacity: 0;
transition: all 0.8s
}
button:active:after {
padding: 0;
margin: 0;
opacity: 1;
transition: 0s
}
</style>
</head>
<body>
<h1>Animated Button Example</h1>
<button>Click Here</button>
<p>Click on the above button to see ripple effect</p>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP