Try   HackMD

用 CSS 實作載入動畫

Elantris


實作

外框

.loading {
  position: relative;
  width: 16rem;
  height: 3rem;
  border: 2px solid black;
  border-radius: 0.5rem;
  background: white;
}

進度條

  1. 內層有顏色、會變動的部分
  2. 定位左上、左下為起始點
  3. width 100% 為可變動值
.loading::before {
  content: "";
  position: absolute;
  top: 0.25rem;
  bottom: 0.25rem;
  left: 0;
  width: 100%;
  background: black;
}

動畫

  1. 用動畫改變 width
  2. timing-function 用 steps() 製造頓點
@keyframes growWidth {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}
.loading::before {
  /* ... */
  animation-name: growWidth;
  animation-duration: 4s;
  animation-timing-function: steps(10, jump-start);
  animation-iteration-count: infinite;
}

遮罩

  1. 用漸層背景製造白色、透明區塊
  2. background-size 設為 10% 製造一排透明窗戶蓋在最上方
.loading::after {
  content: "";
  position: absolute;
  inset: 0;
  background-image: linear-gradient(to right, white 0%, white 25%, transparent 25%, transparent 75%, white 75%);
  background-size: 10% 100%;
}

完整程式碼

Pure CSS Loading Bar