js循环精灵图

<!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++){
//            让索引号乘以44,就是每个li的背景y坐标,index就是y坐标
             var index=i*44;
            lis[i].style.backgroundPosition='0 -'+index+'px';
        }
    </script>
</body>
</html>

 

猜你喜欢

转载自www.cnblogs.com/yueranran/p/11968659.html