一般來說,我們製作按鈕時往往需要兩張圖片——一張是正常狀態,另一張是按下時的效果圖。常見的思路是:把第一張圖設為連結 a 的背景,再把第二張圖設為 a:hover 的背景。


程式碼如下:
HTML 代碼:
<a id="theLink"></a>
CSS 代碼:
#theLink{
display:block;/*因為標籤 a 是內鏈元素,所以利用這句話將它轉化成塊狀元素,後面的 width 和 height 才會生效*/
width:120px;
height:41px;
margin:0 auto;
background:url(../images/normal.gif) no-repeat;
}
#theLink:hover{ background:url(../images/press.gif) no-repeat;}
原始碼下載:兩張圖片按鈕的源代碼.rar (5.2 KB)
=========================================================
接下來,本節要重點介紹第二種思路,其實也很簡單。首先,我們把上面的兩張圖片合併成一張,如下:

接著,把這張合併後的圖片設為按鈕的背景;最後,只需讓 a:hover 的背景向上移動 41 個像素就大功告成了。
HTML 代碼:
<a id="buttonBlock"></a>
CSS 代碼:
#theLink{
display:block;
width:120px;
height:41px;
margin:0 auto;
background:url(../images/buttonBG.gif) no-repeat;
}
#theLink:hover{ background:url(../images/buttonBG.gif) no-repeat 0 -41px;}
如果講到這裡你還不能完全理解,別擔心——下載原始碼一看,保證你立刻豁然開朗。原始碼下載:單張圖片按鈕的源代碼.rar (4.48 KB)。