前言
Hello!小夥伴!
非常感謝您閱讀海轟的文章,倘若文中有錯誤的地方,歡迎您指出~
自我介紹 ଘ(੭ˊᵕˋ)੭
昵稱:海轟
标簽:程式猿|C++選手|學生
簡介:因C語言結識程式設計,随後轉入計算機專業,有幸拿過國獎、省獎等,已保研。目前正在學習C++/Linux(真的真的太難了~)
學習經驗:紮實基礎 + 多做筆記 + 多敲代碼 + 多思考 + 學好英語!
【動畫消消樂】 平時學習生活比較枯燥,無意之間對一些網頁、應用程式的過渡/加載動畫産生了濃厚的興趣,想知道具體是如何實作的? 便在空閑的時候學習下如何使用css實作一些簡單的動畫效果,文章僅供作為自己的學習筆記,記錄學習生活,争取了解動畫的原理,多多“消滅”動畫!
效果展示
Demo代碼
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<section><span></span></section>
</body>
</html>
CSS
html, body {
margin: 0;
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
background: #ed556a;
/* background-color: #82466e; */
animation: backColor 4s infinite;
}
section {
width: 650px;
height: 300px;
padding: 10px;
position: relative;
display: flex;
align-items: center;
justify-content: center;
border: 2px solid white;
}
span {
width: 5px;
height: 5px;
display: inline-block;
position: relative;
border-radius: 4px;
color: white;
background: currentColor;
animation: animloader66 0.6s 0.6s linear infinite alternate;
}
span::before, span::after {
content: '';
width: 5px;
height: 5px;
border-radius: 4px;
background: currentColor;
position: absolute;
left: 0;
top: 15px;
animation: animloader66 0.6s 0.9s linear infinite alternate;
}
[data-index="66"] {
justify-content: normal;
padding-left: 15%;
}
span::after {
top: -15px;
animation-delay: 0s;
}
@keyframes animloader66 {
0% {
width: 5px;
}
100% {
width: 48px;
}
}
原理詳解
步驟1
使用span标簽,設定為
- 相對定位
- 寬度、高度均為5px
- 背景色:白色
- color:白色
- border-radius: 4px
span {
width: 5px;
height: 5px;
position: relative;
border-radius: 4px;
color: white;
background: white;
}
效果圖如下
步驟2
為span添加動畫
動畫描述效果為:span寬度從5px變化到48px,再回到5px
span {
animation: loading 0.6s 0s linear infinite alternate;
}
@keyframes loading {
0% {
width: 5px;
}
100% {
width: 48px;
}
}
注:span事先是設定固定在頁面正中的,是以才會出現上圖效果
步驟3
使用span的兩個僞元素:span::before、span::after
同時設定為
- 絕對定位( left: 0 top: 15px)
span::before, span::after {
content: '';
width: 5px;
height: 5px;
border-radius: 4px;
background: white;
position: absolute;
left: 0;
top: 15px;
}
位置關系如下
為span::before、span::after添加同span一樣的動畫,隻是動畫開始延遲時間設定為0.6s
span::before, span::after {
animation: loading 0.6s 0.6s linear infinite alternate;
}
效果圖如下:
注:可以發現,span和它的兩個僞元素的左部分一直是處于同一條直線上
步驟4
分離span::before、span::after
将span::after移動至位于span上方15px處 且動畫延遲時間修改為0.9s
span::after {
top: -15px;
animation-delay: 0.9s;
}
得到最終的效果圖
結語
文章僅作為學習筆記,記錄從0到1的一個過程
希望對您有所幫助,如有錯誤歡迎小夥伴指正~
我是海轟ଘ(੭ˊᵕˋ)੭,如果您覺得寫得可以的話,請點個贊吧
謝謝支援❤️