無意間發現了一個很神奇的事情,就是

鼠標懸停在圖片上方會切換,起初以為圖標是單獨插入的。但發現居然是一張完整的圖片。

一萬只草泥馬在心中奔騰。這是怎麼實現的?
後來詢問得知,這是css精靈技術(sprite) 也叫雪碧圖。
CSS知識點:
於是,我百度之後。我決定玩一玩
HTML結構
<ul> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> </ul>
css
<style>
ul{
position: absolute;
top: 50px;
height:31px;
}
li{
list-style: none;
float:left;
width:30px;
height: 31px;
margin-right: 30px;
}
a{
width:30px;
height: 31px;
display: block;
background: url(images/social-media.png) no-repeat;
background-position: 8px 0px;
}
</style>
用css來定位坐標的話,十分浪費時間,於是可以用jquery統一設置坐標(ss雪碧圖的定位參數按實際需求)
<script>
$(function() {
var index;
var icorW;
$("ul>li").each(function(index) {
index = $(this).index();//獲取對象的索引值
icorW = $(this).width()+2;//獲取對象寬度
var _this = $(this);
$(_this).children().attr("style","background-position:"+(8-(index *icorW))+"px 0px");//先眾神歸位
$(_this).hover(function () {
$(_this).children().attr("style","background-position:"+(8-(index *icorW))+"px 103%");
$("span").html(index);//測試索引數值
},function(){
$(_this).children().attr("style","background-position:"+(8-(index *icorW))+"px 0px");
})
})
})
</script>