javascript自定義右鍵選單程式碼

admin發表於2017-02-19

右鍵選單這個再熟悉不過了,使用電腦的話每天幾乎都要操作上千遍右鍵選單,下面分享一段自定義右鍵選單的程式碼例項,希望能夠給需要相關內容的朋友帶來幫助,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>螞蟻部落</title>
<style type="text/css">
#d1{
  width:100px;
  height:200px;
  background-color:green;
  display:none;
}
#dl a{
  display:block;
}
</style>
<script type="text/javascript">
window.onload=function(){
  rightmenu('p1','d1');
}
  
function rightmenu(elementID,menuID){
  var menu=document.getElementById(menuID); //獲取選單物件
 var element=document.getElementById(elementID);//獲取點選擁有自定義右鍵的 元素
 //設定該元素的 按下滑鼠右鍵右鍵的 處理函式
  element.onmousedown=function(aevent){
    //解決相容性
   if(window.event)aevent=window.event;
    //當事件屬性button的值為2時,表使用者按下了右鍵      
    if(aevent.button==2){                   
      document.oncontextmenu=function(aevent){
        if(window.event){
           aevent=window.event;
                   //對IE 中斷 預設點選右鍵事件處理函式
       aevent.returnValue=false;         
      }
         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);
  }
}
  
</script>
</head>
<body>
<p id="p1">對我右鍵出現選單</p>
<div id="d1">
   <a>剪下</a>
   <a>複製</a>
   <a>貼上</a>
</div>
</body>
</html>

相關文章