CSS Sprite 图标

HTML

 1 <body>
 2     <!-- ul.sprite>li*5>s.s-icon+a{CSS Sprite} -->
 3     <!-- 以上是Sublime Text快速拼写 -->
 4     <ul class="sprite">
 5         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
 6         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
 7         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
 8         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
 9         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
10         <div class="clear"></div>
11     </ul>
12 </body>

CSS

 1 <style>
 2     body { background-color: #fc0; color:#333;}
 3     * {margin:0; padding:0;}
 4     ul,li {list-style: none;}
 5     a { color:#f00; font-weight: bold; text-decoration: none;}
 6     .sprite {margin:0 auto; width:1000px; padding-top: 50px;}
 7     .sprite li {float:left; margin-left: 50px; text-align: center; cursor:pointer; }
 8     .sprite li s { display: block; width:132px; height:112px; background:url(all.png) no-repeat; }
 9     .clear { clear:both;}
10 </style>

JS

 1 <script src="http://code.jquery.com/jquery-latest.js"></script>
 2     <script>
 3     $(function () {
 4         var iconH = $(".sprite").find("s").height(),
 5             //找出存放图片的容器的高度;
 6             triggerLi = $(".sprite").children("li");
 7             //找出每一个li,放到一个数组中;
 8         //console.log(iconH);
 9         //在控制台打印出容器的高度;
10         triggerLi.each(function () {
11         //遍历数组中的每一个li
12             var $this = $(this),
13                 //声明变量赋值当前的li;
14                 $index = $this.index();
15                 //声明变量保存当前li的index值;
16             //console.log($index);
17             //在控制台打印出每一个li的index值;
18             //console.log(iconH*$index);
19             //得出每一个图片对应的position值;
20             $this.children("s").css("background-position","0 -"+iconH*$index+"px");
21             //利用js遍历出每一个s标签的背景图片;
22             $this.hover(function() {
23                 //鼠标移入
24                 $this.children("s").css("background-position","-132px -"+iconH*$index+"px");
25             }, function() {
26                 //鼠标移出
27                 $this.children("s").css("background-position","0 -"+iconH*$index+"px");
28             });
29         })
30     })
31     </script>

IMG(右键保存即可,重命名all.png)

SHOW

 

posted @ 2014-12-09 21:00  翌子涵  阅读(640)  评论(0编辑  收藏  举报