前言

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;
} section {
width: 650px;
height: 300px;
padding: 10px;
position: relative;
display: flex;
align-items: center;
justify-content: center;
border: 2px solid white;
} span {
width: 64px;
height: 64px;
display: inline-block;
position: relative;
} span::after {
content: '';
width: 32px;
height: 32px;
position: absolute;
left: 0;
top: 0;
background: white;
color: white;
animation: loading 2s linear infinite alternate;
} @keyframes loading {
0% {
box-shadow: 0 0, 0 0, 0 0
}
33% {
box-shadow: 32px 0px, 32px 0px, 32px 0px
}
66% {
box-shadow: 32px 32px, 32px 32px, 32px 0px
}
100% {
box-shadow: 0px 32px, 32px 32px, 32px 0px
}
}

原理詳解

步驟1

使用span標籤,設定為

  • 寬度、高度均為64px
  • 相對定位
  • 背景色:goldenrod
span {
width: 64px;
height: 64px;
position: relative;
background-color:goldenrod;
}

效果圖如下

步驟2

使用span::after偽元素,設定為

  • 絕對定位(top:0 left:0)
  • 寬度、高度均為32px(大小是span的四分之一
  • 背景色:白色
  • color:白色
span::after {
content: '';
width: 32px;
height: 32px;
position: absolute;
left: 0;
top: 0;
background: white;
color: white;
}

效果圖如下

步驟3

使用span::after的陰影(box-shadow) 需要三個

位置分別是(注意是span::after的陰影):

/*陰影1*/
32px 0px , /*陰影2*/
32px 32px , /*陰影3*/
0px 32px ;

理論圖如下

步驟4

利用步驟3的三個陰影組成動畫

陰影均為白色(步驟3是為了區分不同陰影而採用的彩色)

有關鍵四幀

第一幀

  • 陰影1、2、3均不顯示
box-shadow: 0 0, 0 0, 0 0

效果圖如下



第二幀

  • 顯示陰影1
  • 陰影2、3不顯示
box-shadow: 32px 0px, 32px 0px, 32px 0px

效果圖如下

第三幀

  • 顯示陰影1、2
  • 陰影3不顯示
 box-shadow: 32px 32px, 32px 32px, 32px 0px

效果圖如下

第四幀

  • 同時顯示陰影1、2、3
  box-shadow: 0px 32px, 32px 32px, 32px 0px

效果圖如下

動畫從第一幀逐步過渡至第四幀

span::after {
animation: loading 2s linear infinite alternate;
}
@keyframes loading {
0% {
box-shadow: 0 0, 0 0, 0 0
}
33% {
box-shadow: 32px 0px, 32px 0px, 32px 0px
}
66% {
box-shadow: 32px 32px, 32px 32px, 32px 0px
}
100% {
box-shadow: 0px 32px, 32px 32px, 32px 0px
}
}

效果圖如下

步驟5

動畫採用alternate交替

animation: loading 2s linear infinite alternate;

效果圖如下

步驟6

去掉span背景色

最後效果圖如下

結語

文章僅作為學習筆記,記錄從0到1的一個過程

希望對您有所幫助,如有錯誤歡迎小夥伴指正~

我是海轟ଘ(੭ˊᵕˋ)੭,如果您覺得寫得可以的話,請點個贊吧

謝謝支援️