效果实现
案例分析
1.获取元素 所有的li
2.使用for循环来设置每个li的背景图
3.通过设置精灵图的y坐标来设置不同li的背景图
4.让索引号*44就是每个li的背景y坐标,index就是我们的y坐标
代码展示
<!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>
<style>
* {
list-style: none;
margin: 0;
padding: 0;
}
.box {
width: 250px;
margin: 100px auto;
}
.box li {
width: 24px;
height: 24px;
background-color: pink;
margin: 15px;
background: url(jl.png) no-repeat;
}
</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>
// 1.获取元素 所有的li
var list = document.querySelectorAll('li');
// 2.使用for循环来设置每个li的背景图
for (var i = 0; i < list.length; i++) {
// 通过设置精灵图的y坐标来设置不同li的背景图
// 让索引号*44就是每个li的背景y坐标,index就是我们的y坐标
var index = i * 44;
list[i].style.backgroundPosition = '0 -' + index + 'px';
}
</script>
</body>
</html>