有些特效的巧思不在程式碼量,而在視覺隱喻。DotMenu 就是把選單的框線拆成一顆顆 6×6 像素的小方點,滑鼠移過時讓點逐一亮起,形成類似跑馬燈描邊的效果;選單本體與說明文字則用獨立的圖層定位在點的外側。
點分成三種狀態:.dot 是紅色可點擊的、.dotoff 是灰色的停用點、.dotempty 是橙色的裝飾點;.caption 則是說明文字。共同點是都採用絕對定位、初始 visibility:hidden,並用 z-index 決定層疊順序。
<style type="text/css">
.dot {
position:absolute; width:6px; height:6px; visibility:hidden;
background-color:red; font-size:1px; cursor:pointer; z-index:100;
}
.dotoff {
position:absolute; width:6px; height:6px; visibility:hidden;
background-color:gray; font-size:1px; cursor:default; z-index:100;
}
.dotempty {
position:absolute; width:6px; height:6px; visibility:hidden;
background-color:orange; font-size:1px; cursor:pointer; z-index:100;
}
.caption {
position:absolute; visibility:hidden; font-family:Tahoma;
color:black; font-size:11px; text-align:center;
cursor:default; z-index:1;
}
body { margin:0px; background-color:white; }
a { color:silver; text-decoration:none; }
p { font-size:10px; font-family:tahoma; color:black; }
</style>
選單要能跑在不同年代的瀏覽器上,第一個要解決的就是「怎麼抓到元素」。getObjectRef() 依序嘗試 getElementById 與 document.all,這正是 W3C 標準與 IE 私有 API 並存時代的典型寫法。有了它,顯示、隱藏與量測尺寸就都只要一行:
function getObjectRef(name) {
if (document.getElementById) return document.getElementById(name);
else if (document.all) return document.all[name];
else return null;
}
function show(name) {
var el = getObjectRef(name);
if (el) el.style.visibility = "visible";
}
function hide(name) {
var el = getObjectRef(name);
if (el) el.style.visibility = "hidden";
}
function getWidth(name) { return getObjectRef(name).offsetWidth; }
function getHeight(name) { return getObjectRef(name).offsetHeight; }
原始版本還附上一段 lib_bwcheck() 的瀏覽器偵測,逐一判斷 MSIE 5、MSIE 6、Opera 5、document.layers 等特徵來決定分支走向。這種以「偵測瀏覽器」為前提的寫法今天已經被淘汰,取而代之的是偵測「功能是否存在」——也就是像 if (document.getElementById) 這樣的判斷,或直接交給 querySelector 處理。
核心概念很好移植:用一個容器元素把大量小方塊絕對定位排成框線,再用 setInterval 依序切換某顆點的 background-color,就是描邊跑馬燈;把滑鼠移到容器上時啟動、移開時停止即可。若不想產生上百個 DOM 節點,也可以改用 border-image 或 background-image 搭配點狀圖,並以 CSS @keyframes 控制 background-position 位移,效能會好上許多。