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

參考

參考鏈接
「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 代碼

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

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

效果展示

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值