參考
參考 | 鏈接 |
---|---|
「HTML+CSS」–自定义加载动画【007】 | https://cloud.tencent.com/developer/article/1811548 |
CSS3 animation(动画) 属性 | https://www.runoob.com/cssref/css3-pr-animation.html |
核心原理
其實這個功能相對很簡單,只是看到好玩想說自己實踐下順扁做個紀錄而已。其實原理就只是通過 span
和 span::after
以及簡單的 css3 動畫而已,很間單的。下面一步步來看看怎麼做的!
html 代碼
<!-- loading.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">
<title>Document</title>
<link rel="stylesheet" href="loading.css">
</head>
<body>
<span></span>
</body>
</html>
css 代碼
/* loading.css */
html, body {
margin: 0;
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
background: #263238;
}
span {
width: 120px;
height: 120px;
border: 10px solid transparent;
display: flex;
align-items: center;
justify-content: center;
position: relative;
border-bottom-color: orange;
border-radius: 50%;
animation: loading 2s linear infinite;
}
span::after {
position: relative;
content: "";
display: inline-block;
width: 96px;
height: 96px;
border: 10px solid #fff;
border-radius: 50%;
}
@keyframes loading {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
下面拆解下怎麼寫出上面代碼的。
Step1
首先先把 span
設置大小,弄出一個邊框來。
span {
width: 120px;
height: 120px;
border: 10px solid #fff;
}
Step2
基於 Step1 的外框在裡面弄出一個內框,與外框要留有一些間隙。這邊就使用到 css 的偽元素 ::
。
span {
width: 120px;
height: 120px;
border: 10px solid #fff;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
span::after {
position: relative;
content: "";
display: inline-block;
width: 96px;
height: 96px;
border: 10px solid #fff;
}
Step3
這一步要把 1/4 的外框變成有色的。
border-bottom-color: orange;
Step4
然後把內框和外框都做圓角設置。
border-radius: 50%;
Step5
把外框樣式變得透明。
border: 10px solid transparent;
這邊有個小技巧,就是雖然我們在 span
上這麼設置了 border
,但因為 border-bottom-color
設置了顏色所以依然會顯示。
Step6
最後就是添加動畫,這邊使用到了 css3 的 animation
屬性,配合 @keyframes
。
animation: loading 2s linear infinite;
@keyframes loading {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
到這邊就都大功搞成啦~最後來看看最終的效果圖!