题目:循环精灵图背景
作用:利用for循环设置一组元素的精灵图背景
图片:
分析:
- 首先精灵图图片排列有规律
- 核心思路:利用for循环 修改精灵图的背景位置 background-position(第i个小图标的位置为0-i*44)
效果:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>循环精灵图</title>
<style>
ul {
list-style-type: none;
padding-left: 0;
}
.box {
width: 250px;
margin: 100px auto;
}
.box li {
float: left;
width: 24px;
height: 24px;
background-color: pink;
margin: 15px;
background: url(images/精灵图.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>
var lis = document.querySelectorAll('li');
for(var i = 0;i < lis.length;i++) {
var index = i*44;
//注意不要有多余的空格
lis[i].style.backgroundPosition = '0 -' + index + 'px';
}
</script>
</body>
</html>