一、一些概念:
1、鼠標(biāo)事件有一個botton屬性:返回一個整數(shù),用于表示點擊的是哪個鼠標(biāo)按鍵。
BUG:在IE和標(biāo)準(zhǔn)DOM的鼠標(biāo)事件中,唯一一個button屬性值相同的是“單擊右鍵”事件,都返回2。
2、事件onmousedown:表示鼠標(biāo)按鍵按下的動作。
事件oncontextmenu:點擊鼠標(biāo)觸發(fā)的另一個事件。
3、中斷默認(rèn)事件處理函數(shù)的方法:IE中設(shè)置returnValue=false; 標(biāo)準(zhǔn)DOM中調(diào)用prevemtDefault()方法。
4、事件對象:①在IE中,事件對象是window對象的一個event屬性。
聲明:
②在標(biāo)準(zhǔn)DOM中,事件對象是事件處理函數(shù)的唯一參數(shù)。
聲明:
解決兼容性:
二、實現(xiàn):
HTML:
<p id="p1">Uncle Cat is a fat white cat !</p> <div id="d1"> <a>剪切</a> <a>復(fù)制</a> <a>粘貼</a> </div>
javascript:
window.onload=function(){ rightmenu('p1','d1'); } /**** * 封裝右鍵菜單函數(shù): *elementID 要自定義右鍵菜單的 元素的id *menuID 要顯示的右鍵菜單DIv的 id */
function rightmenu(elementID,menuID){ var menu=document.getElementById(menuID); //獲取菜單對象 var element=document.getElementById(elementID);//獲取點擊擁有自定義右鍵的 元素 element.onmousedown=function(aevent){ //設(shè)置該元素的 按下鼠標(biāo)右鍵右鍵的 處理函數(shù) if(window.event)aevent=window.event; //解決兼容性 if(aevent.button==2){ //當(dāng)事件屬性button的值為2時,表用戶按下了右鍵 document.oncontextmenu=function(aevent){ if(window.event){ aevent=window.event; aevent.returnValue=false; //對IE 中斷 默認(rèn)點擊右鍵事件處理函數(shù) }else{ aevent.preventDefault(); //對標(biāo)準(zhǔn)DOM 中斷 默認(rèn)點擊右鍵事件處理函數(shù) }; }; menu.style.cssText='display:block;top:'+aevent.clientY+'px;'+'left:'+aevent.clientX+'px;' //將菜單相對 鼠標(biāo)定位 } } menu.onmouseout=function(){ //設(shè)置 鼠標(biāo)移出菜單時 隱藏菜單 setTimeout(function(){menu.style.display="none";},400); } }