無意間發現一個有趣的現象:滑鼠移到圖示上會切換圖案,原本以為是兩張圖片疊在一起,仔細一看卻發現——那其實是同一張完整的大圖。


後來詢問才知道,這就是 CSS 精靈技術(sprite),中文常譯為雪碧圖。
background-imagebackground-position<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>
<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>
一張張手寫 background-position 既費時又容易出錯。既然每個項目的寬度一致,與其硬算,不如讓程式去算:
<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>
關鍵在 8 - (index * icorW) 這條算式:起始偏移量 8 減去「索引 × 單項寬度」,就能精準落在第 index 張圖上。垂直方向則用 0px 與 103% 分別對應精靈圖的上下兩排狀態。
小提醒:這裡用 attr("style", ...) 直接覆寫整段 style,實務上更乾淨的做法是用 .css("background-position", ...),避免把元素原有的其他行內樣式一起洗掉。