純前端 - 原生自定義加載動畫
发布日期:2021-05-04 19:51:27 浏览次数:16 分类:精选文章

本文共 1918 字,大约阅读时间需要 6 分钟。

純前端 - 原生自定義加載動畫

參考

參考 鏈接
「HTML+CSS」–自定义加载动画【007】 https://cloud.tencent.com/developer/article/1811548
CSS3 animation(动画) 属性 https://www.runoob.com/cssref/css3-pr-animation.html

核心原理

其實這個功能相對很簡單,只是看到好玩想說自己實踐下順扁做個紀錄而已。其實原理就只是通過 spanspan::after 以及簡單的 css3 動畫而已,很間單的。下面一步步來看看怎麼做的!

html 代碼

Document

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);  }}

到這邊就都大功搞成啦~最後來看看最終的效果圖!

效果展示

上一篇:Axios 如何取消重複請求
下一篇:理解虛擬 DOM 原理以及簡單實現

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月14日 18时43分38秒