利用 jQuery 的 .hover() 方法,僅需幾行代碼即可實現導航項目滑鼠進入/離開時平滑切換背景圖片。本文提供完整可運行範例,並說明 CSS Sprite 更佳的效能做法。
$(function() {
$('.nav-item').hover(
function() { $(this).css('background-image', 'url(hover.png)'); },
function() { $(this).css('background-image', 'url(default.png)'); }
);
});
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<style>
.nav { display:flex; gap:10px; padding:20px; }
.nav-item {
width:100px; height:40px; line-height:40px; text-align:center;
background:url(default.png) no-repeat center; color:#333; cursor:pointer;
transition: background 0.3s; /* 添加過渡動畫 */
}
.nav-item a { color:inherit; text-decoration:none; display:block; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head><body>
<ul class="nav">
<li class="nav-item"><a href="#">首頁</a></li>
<li class="nav-item"><a href="#">產品</a></li>
<li class="nav-item"><a href="#">關於</a></li>
</ul>
<script>
$('.nav-item').hover(
() => $(this).css('background-image', 'url(hover.png)'),
() => $(this).css('background-image', 'url(default.png)')
);
</script>
</body></html>
將預設態與懸停態合併為單一圖片,利用 background-position 切換,減少 HTTP 請求並消除首次懸停的圖片載入延遲:
.nav-item { background: url(sprite.png) no-repeat 0 0; }
.nav-item:hover { background-position: 0 -40px; } /* 假設高度 40px */
此時 JS 甚至不需要,純 CSS 即可完成,效能最佳。
.nav-item:focus-within 或 a:focus。<a> 內加入文字或 aria-label。