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

// 通用獲取元素
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"); };
};
<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>
background-position: -300px 0 即顯示第二狀態。DD_belatedPNG 或 AlphaImageLoader hack 處理 PNG 透明。若需更炫酷效果(氣泡提示、動畫過渡),推薦參考 cssrain 的 jQuery 氣泡提示;但對於極簡場景,本方案 20 行 JS 即可搞定,性能無負擔。