<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>用for循环填充精灵图</title> <style type="text/css"> #box{ width: 250px; margin: 100px auto; } #box li{ width: 24px; height: 24px; float: left; margin: 10px; background-color: pink; list-style-type: none; background: url(img/taobaojinglingtu.png) no-repeat; } </style> </head> <body> <div id="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 type = "text / JavaScript" > var LIS = document.querySelectorAll ( ' Li ' ); for ( var I = 0 ; I < lis.length; I ++ ) { // make the index number is multiplied by 44, is the y coordinate of each li background,is the index y coordinate var index=i*44; lis[i].style.backgroundPosition='0 -'+index+'px'; } </script> </body> </html>
‘