萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> 互動設計

CSS Sprite + 原生 JS 實現滑鼠懸停無縫切換效果

結合 CSS Sprite 技術與極簡原生 JS,打造零依賴、高性能的導航懸停切換效果。附帶 IE6 PNG 透明兼容方案,適合追求極致輕量的專案。

效果預覽

效果截圖

核心 JS(含跨瀏覽器 $ 封裝)

// 通用獲取元素
function $(objectId) {
  if (document.getElementById && document.getElementById(objectId)) return document.getElementById(objectId);
  if (document.all && document.all(objectId)) return document.all(objectId);
  if (document.layers && document.layers[objectId]) return document.layers[objectId];
  return false;
}

// 切換文字與背景定位
function iLeftNav(type) {
  var inum, info = $("i_navinfo");
  switch (type) {
    case "writeblog": inum = "-300px"; break;
    case "sharepic":  inum = "-600px"; break;
    case "writemsg":  inum = "-900px"; break;
    default:          inum = "-300px";
  }
  info.innerHTML = $(type).innerHTML;
  info.style.backgroundPosition = inum + " 0";
}

// 綁定懸停事件
window.onload = function() {
  var items = $("i_blognav").getElementsByTagName("li");
  items[0].onmouseover = function() { iLeftNav("writeblog"); };
  items[1].onmouseover = function() { iLeftNav("sharepic"); };
  items[2].onmouseover = function() { iLeftNav("writemsg"); };
};

HTML 結構示意

<ul id="i_blognav">
  <li id="writeblog">寫文章</li>
  <li id="sharepic">分享圖片</li>
  <li id="writemsg">寫留言</li>
</ul>
<div id="i_navinfo" class="sprite-bg">預設文字</div>

CSS Sprite 關鍵點

  • 單張大圖垂直拼接三種狀態,每狀態高 300px。
  • background-position: -300px 0 即顯示第二狀態。
  • IE6 需引入 DD_belatedPNG 或 AlphaImageLoader hack 處理 PNG 透明。

進階建議

若需更炫酷效果(氣泡提示、動畫過渡),推薦參考 cssrain 的 jQuery 氣泡提示;但對於極簡場景,本方案 20 行 JS 即可搞定,性能無負擔。

copyright © 萬盛學電腦網 all rights reserved