<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>循环精灵图</title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style-type: none;
}
.box {
width: 400px;
margin: 100px auto;
}
.box li {
float: left;
width: 100px;
height: 100px;
background-color: rgb(112, 128, 216);
margin: 15px;
background: url(../img/logo.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>
</ul>
</div>
<script>
//1、获取元素
var lis = document.querySelectorAll("li");
for (var i = 0; i < lis.length; i++) {
var index = i * 100; //index是Y坐标,让找到的图片依次增加y坐标(每次乘以等量的间距)
lis[i].style.backgroundPosition = '0 -' + index + 'px';
}
</script>
</body>
</html>
成功
展示: