HTML中自訂右鍵菜單功能
我們使用的應用系統很多都有右鍵菜單功能。但是在網頁上面,點擊右鍵一般顯示的卻是IE預設的右鍵菜單,那麼我們如何?自己的右鍵菜單呢?下面將講解右鍵菜單功能的實現原理和實現代碼。
實現原理
在HTML語言中,基本上每個對象都有一個oncontextmenu事件,這個事件就是滑鼠的按右鍵事件(onclick事件是滑鼠的左鍵單擊事件),那麼我們就可以在滑鼠右擊的時候,讓系統彈出一個視窗(這個是popup視窗,顯示在IE的最前面,沒有菜單),上面顯示我們想要顯示的菜單資訊,當我們單擊其中某一項的時候,就執行我們設定的動作,然後將快顯視窗關閉。
實現代碼
下面我寫了一個範例程式碼,類比一個多層div,當我們右鍵點擊多層div某一項的時候,就會彈出右鍵菜單,裡面有“creat row”、“ modify row”、“delete row” 三個功能表項目,單擊某項會執行相應的操作。下面的代碼內容:
首先,我們需要編輯一個右鍵菜單,並且將其隱藏,需要時再彈出。
<div id="itemMenu" style="display:none">
<table border="1" width="100%" height="100%" bgcolor="#cccccc" style="border:thin" cellspacing="0">
<tr>
<td style="cursor:default;border:outset 1;" align="center" onclick="parent.create()">
creat row
</td>
</tr>
<tr>
<td style="cursor:default;border:outset 1;" align="center" onclick="parent.update();">
modify row
</td>
</tr>
<tr>
<td style="cursor:default;border:outset 1;" align="center" onclick="parent.del();">
delete row
</td>
</tr>
</table>
</div>
其次,將首頁面的多層div羅列出來。
<div dojoType="ContentPane" label="My Widgets" id="main" oncontextmenu = "javascript:showMenu();">
<div id="xml" oncontextmenu = "javascript:showMenu();">
<div id="grp1" class="module">
accepts xml box
</div>
</div>
<div id="database" oncontextmenu = "javascript:showMenu();">
<div id="grp3"class="module">
accepts DataBase box
</div>
</div>
<div id="rss" oncontextmenu = "javascript:showMenu();">
<div id="grp2" class="module">
accepts RSS box
</div>
</div>
</div>
最後,也是關鍵區段,使用JavaScript編寫函數部分。
<script language="JavaScript">
function showMenu()
{
popMenu(itemMenu,100,"111");
event.returnValue=false;
event.cancelBubble=true;
return false;
}
/**
*顯示快顯功能表
*menuDiv:右鍵菜單的內容
*width:行顯示的寬度
*rowControlString:行控制字元串,0表示不顯示,1表示顯示,如“101”,則表示第1、3行顯示,第2行不顯示
*/
function popMenu(menuDiv,width,rowControlString)
{
//建立快顯功能表
var pop=window.createPopup();
//設定快顯功能表的內容
pop.document.body.innerHTML=menuDiv.innerHTML;
var rowObjs=pop.document.body.all[0].rows;
//獲得快顯功能表的行數
var rowCount=rowObjs.length;
//迴圈設定每行的屬性
for(var i=0;i<rowObjs.length;i++)
{
//如果設定該行不顯示,則行數減一
var hide=rowControlString.charAt(i)!='1';
if(hide){
rowCount--;
}
//設定是否顯示該行
rowObjs[i].style.display=(hide)?"none":"";
//設定滑鼠滑入該行時的效果
rowObjs[i].cells[0].onmouseover=function(){
this.style.background="#818181";
this.style.color="white";
}
//設定滑鼠滑出該行時的效果
rowObjs[i].cells[0].onmouseout=function(){
this.style.background="#cccccc";
this.style.color="black";
}
}
//屏蔽菜單的菜單
pop.document.oncontextmenu=function(){
return false;
}
//選擇右鍵菜單的一項後,菜單隱藏
pop.document.onclick=function(){
pop.hide();
}
//顯示菜單
pop.show(event.clientX-1,event.clientY,width,rowCount*25,document.body);
return true;
}
function create(){
alert("create" );
}
function update(){
alert("update" );
}
function del(){
alert("delete" );
}
</script>
小結:本文的重點是如何?自訂的右鍵菜單,以及對右鍵功能表項目的操作。通過本文的例子,相信大家已經學會oncontextmenu 和 popMenu的使用方法。也希望大家學會靈活運用執行個體。