klren0312 / daliy_knowledge

知识积累,正确使用方式是watch
21 stars 4 forks source link

页面实现电池进度条效果 #813

Open klren0312 opened 6 months ago

klren0312 commented 6 months ago

1710126133083

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
  .battery-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #000000;
    border: 1px solid #999;
    padding: 5px;
    width: 200px;
    height: 30px;
    overflow: hidden;
  }

  .battery-cell {
    width: 7px;
    height: 20px;
    margin-right: 3px;
    background-color: #666;
    border-radius: 5px;
  }

  /* 使用伪类选择器控制不同电量等级的颜色 */
  .battery-cell.full {
    background-color: #ff0000;
  }
</style>
</head>
<body>

<div class="battery-container">
  <!-- 固定数量的电池格子 -->
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
  <div class="battery-cell"></div>
</div>

<script>
  // 假设 batteryLevel 是获取到的当前电量百分比
  let batteryLevel = 10 // 实际应从某个数据源获取

  // 获取所有的电池格子
  const batteryCells = document.querySelectorAll('.battery-cell')
  const length = batteryCells.length
  // 计算占用的格子
  const filledCells = Math.ceil(length * (batteryLevel / 100))
  // 根据电量百分比设置对应格子为“充满”状态
  for (let i = 0; i < filledCells; i++) {
    batteryCells[i].classList.add('full')
  }
</script>

</body>
</html>