CSS Sprite 图标

时间:2023-03-08 17:35:38
CSS Sprite 图标

HTML

 <body>
<!-- ul.sprite>li*5>s.s-icon+a{CSS Sprite} -->
<!-- 以上是Sublime Text快速拼写 -->
<ul class="sprite">
<li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
<li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
<li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
<li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
<li><s class="s-icon"></s><a href="">CSS Sprite</a></li>
<div class="clear"></div>
</ul>
</body>

CSS

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

JS

 <script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function () {
var iconH = $(".sprite").find("s").height(),
//找出存放图片的容器的高度;
triggerLi = $(".sprite").children("li");
//找出每一个li,放到一个数组中;
//console.log(iconH);
//在控制台打印出容器的高度;
triggerLi.each(function () {
//遍历数组中的每一个li
var $this = $(this),
//声明变量赋值当前的li;
$index = $this.index();
//声明变量保存当前li的index值;
//console.log($index);
//在控制台打印出每一个li的index值;
//console.log(iconH*$index);
//得出每一个图片对应的position值;
$this.children("s").css("background-position","0 -"+iconH*$index+"px");
//利用js遍历出每一个s标签的背景图片;
$this.hover(function() {
//鼠标移入
$this.children("s").css("background-position","-132px -"+iconH*$index+"px");
}, function() {
//鼠标移出
$this.children("s").css("background-position","0 -"+iconH*$index+"px");
});
})
})
</script>

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

CSS Sprite 图标

SHOW

CSS Sprite 图标