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