问题描述:通过JavaScript将精灵图里面的小图标给遍历出来。
关键代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } #box { width: 230px; height: 270px; } #box ul { width: 100%; height: 100%; list-style: none; } #box li { width: 70px; height: 90px; display: block; float: left; text-align: center; } span { width: 24px; height: 44px; display: inline-block; } </style> </head> <body> <div id="box"> <ul> </ul> </div> <script> var box = document.querySelector('#box'); var arr = ['企业购', '礼品卡', '话费', '机票', '游戏', '白条', '火车票', '加油卡', '五金城', '电影票', '酒店', '云建站']; var html = ''; for (var i = 0; i < arr.length; i++) { html += ` <li> <span style='background:url(./sprite.png) no-repeat 0px -${i*43}px'></span> <p>${arr[i]}</p> </li> ` } var ul = document.querySelector('ul'); ul.innerHTML = html; </script> </body> </html>
效果图: