<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>06-循环遍历精灵图</title>

  <style>

    li {
      list-style: none;
    }

    .box ul {
      padding-left: 0px;
      overflow: hidden;
    }

    .box {
      width: 180px;
      background-color: skyblue;
      margin: 100px auto;
    }

    .box li {
      float: left;
      width: 24px;
      height: 24px;
      background-color: pink;
      margin: 10px;
      background: url('imgs/sprite.png');
    }
  </style>
</head>
<body>
  <div class="box">
    <ul>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>

  <script>
    // 获取元素
    const box = document.querySelector('.box');
    let lis = document.querySelectorAll('li');
    // 循环遍历
    for (let i = 0; i < lis.length; i++) {
      // 用.style的方式修改样式属性是直接修改到内联样式
      let index = i * 44;
      // JavaScript修改样式属性采用的是驼峰命名
      lis[i].style.backgroundPosition = '0px -' + index + 'px'
    }
  </script>
</body>
</html>

雪碧图如下:

循环遍历精灵图练习_html