這份範例示範如何從零打造一個自訂的右鍵選單(context menu),而且寫得頗有物件導向的味道:一個 contextMenu 負責管理選單容器與項目清單,另一個 contextItem 負責描述單一項目,兩者各自實作自己的 show() 方法,最後由選單把 HTML 字串寫進文件。
它用陣列收集項目,addItem() 負責加入;show() 則組出一個絕對定位、初始隱藏的 div,高度依項目數量動態計算(每項 20px),中間用幾層 table 做出立體邊框與分隔線,最後遍歷呼叫每個項目的 show()。
<script>
// 選單容器
function contextMenu() {
this.items = new Array();
this.addItem = function (item) {
this.items[this.items.length] = item;
};
this.show = function (oDoc) {
var strShow = "";
strShow += '<div id="rightmenu" style="BACKGROUND-COLOR:#ffffff;'
+ 'BORDER:#000000 1px solid; LEFT:0px; POSITION:absolute;'
+ 'TOP:0px; VISIBILITY:hidden; Z-INDEX:10">';
strShow += '<table border="0" height="' + this.items.length * 20
+ '" cellpadding="0" cellspacing="0">';
strShow += '<tr><td>';
strShow += '<table border="0" width="100%" height="100%"'
+ ' cellpadding="3" cellspacing="0" bgcolor="#ffffff">';
oDoc.write(strShow);
for (var i = 0; i < this.items.length; i++) {
this.items[i].show(oDoc);
}
strShow = '</table></td></tr></table></div>';
oDoc.write(strShow);
};
}
</script>
每個項目接受四個參數:text 文字、icon 圖示、cmd 點擊後要執行的程式碼、type 類型(預設 menu)。當型別是 menu 時,輸出一列 tr,掛上滑鼠移入移出的樣式切換與 onclick,有圖示就放 img,沒圖示就用 佔位對齊。
// 單一選項
function contextItem(text, icon, cmd, type) {
this.text = text ? text : "";
this.icon = icon ? icon : "";
this.cmd = cmd ? cmd : "";
this.type = type ? type : "menu";
this.show = function (oDoc) {
var strShow = "";
if (this.type == "menu") {
strShow += '<tr onmouseover="changeStyle(this, \'on\');"'
+ ' onmouseout="changeStyle(this, \'out\');"'
+ ' onclick="' + this.cmd + '">';
strShow += '<td class="ltdexit" width="16">';
if (this.icon == "") {
strShow += " ";
} else {
strShow += '<img src="' + this.icon + '" height="16" border="0">';
}
strShow += '</td><td>' + this.text + '</td></tr>';
}
oDoc.write(strShow);
};
}
建立物件、加入項目、然後攔下頁面的右鍵叫出選單即可:
<script>
var menu = new contextMenu();
menu.addItem(new contextItem("重新整理", "", "location.reload()"));
menu.addItem(new contextItem("回首頁", "", "location.href='/'"));
menu.addItem(new contextItem("關於本站", "", "alert('關於本站')"));
document.oncontextmenu = function (e) {
menu.show(document);
var m = document.getElementById("rightmenu");
m.style.left = (e.clientX || 0) + "px";
m.style.top = (e.clientY || 0) + "px";
m.style.visibility = "visible";
return false;
};
</script>
第一,changeStyle() 與 .ltdexit 樣式需要另外定義,原範例是靠外部樣式表提供,實作時別忘了補上,否則移入移出不會有視覺回饋。第二,這套以 document.write 組字串的做法在現代專案中並不建議:改用 document.createElement 建立節點、以 addEventListener 綁事件,不僅較不易出錯,也避開了字串拼接可能帶來的注入風險。
最後提醒,完全取代瀏覽器右鍵選單會讓使用者失去「另存圖片」「檢查元素」等常用功能,多數成熟網站只在特定元件(例如圖片編輯器、表格)上自訂選單,並保留其他區域的預設行為,這是比較友善的取捨。