# 使用 css 实现 loading

使用 css 变量实现:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <style>
    .box {
      width: 200px;
      height: 200px;
      background: greenyellow;
      padding: 20px;
      position: relative;
      --percent: 0;
    }
    .container {
      width: calc(100% - 40px);
      height: calc(100% - 40px);
      background: white;
      position: absolute;
    }
    .circle {
      border-radius: 50%;
      overflow: hidden;
    }
    .left,
    .right {
      position: absolute;
      width: 50%;
      height: 100%;
      top: 0;
      background: green;
    }
    .left-mask {
      position: absolute;
      width: 50%;
      height: 100%;
      top: 0;
      left: 0;
      background: greenyellow;
      display: calc(50 - var(--percent));
    }
    .left {
      left: 0;
      transform-origin: right center;
      transform: rotate(calc(var(--percent) / 50 * 180deg));
    }
    .right {
      left: 50%;
      transform-origin: left center;
      transform: rotate(calc(var(--percent) / 50 * 180deg - 180deg));
    }
  </style>
  <body>
    <div class="box circle">
      <div id="left" class="left"></div>
      <div id="right" class="right"></div>
      <div id="mask" class="left-mask"></div>
      <div class="container circle"></div>
    </div>

    <div>
      <button onclick="ro()">rotate</button>
      <p id="txt"></p>
    </div>

    <script>
      function ro() {
        const random = Math.round(Math.random() * 100)
        console.log(random)
        document.getElementById('txt').innerText = random
        if (random > 50) {
          document.getElementById('mask').style.display = 'none'
        } else {
          document.getElementById('mask').style.display = 'block'
        }
        document
          .getElementById('left')
          .setAttribute('style', `--percent:${random <= 50 ? random : 50};`)
        document
          .getElementById('right')
          .setAttribute('style', `--percent:${random - 100};`)
      }
    </script>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88