萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現導航欄滑鼠懸停切換背景圖片效果

利用 jQuery 的 .hover() 方法,僅需幾行代碼即可實現導航項目滑鼠進入/離開時平滑切換背景圖片。本文提供完整可運行範例,並說明 CSS Sprite 更佳的效能做法。

核心邏輯

$(function() {
  $('.nav-item').hover(
    function() { $(this).css('background-image', 'url(hover.png)'); },
    function() { $(this).css('background-image', 'url(default.png)'); }
  );
});

完整 HTML 範例

<!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>

進階優化:CSS Sprite 合併圖片

將預設態與懸停態合併為單一圖片,利用 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。
copyright © 萬盛學電腦網 all rights reserved