1. 程式人生 > >用javascript 實現網頁滑鼠右鍵彈出選單功能

用javascript 實現網頁滑鼠右鍵彈出選單功能

工作中需要實現在網頁上點右鍵彈出簡單選單的功能,在網上找了一些例子,都比較複雜,其實我這邊只需要實現簡單的選單功能,兩個選項,使用者點選了以後實現一些簡單的ajax功能。於是根據思路,用DOM建立一個選單層,每個選單選項有自己的onclick方法,啟用相應的ajax功能,然後將層位置定義到滑鼠點選點的右下方,如果點左鍵,那麼刪除選單。很簡單的就實現了,下面是程式碼:

function setDivRightMenu(divId)
{
    $(divId).mousedown(function(event) {
        if (event.button == 2) {
            //這個很重要,遮蔽系統滑鼠右鍵選單功能

            document.oncontextmenu = hideSysMenu;

            x = event.clientX;
            y = event.clientY;
            CreateMenu(event.target);

            var PopMenu = document.getElementById('div_RightMenu');
            PopMenu.style.left = x - 2;
            PopMenu.style.top = y - 2;
            PopMenu.style.display = 'inline';
        }
        if (event.button == 1) {
            removeDivRightMenu();
        }
    });
   }

   function hideSysMenu() {
       return false;
   }

   function CreateMenu(obj) {
       var div_Menu = document.createElement("Div");
       div_Menu.id = "div_RightMenu";
       div_Menu.className = "div_RightMenu";
       //div_Menu.setAttribute("onMouseOut", "removeDivRightMenu();");

       var div_Menu1 = document.createElement("Div");
       div_Menu1.className = "divMenuItem";
       div_Menu1.onclick = function() { selectDivRightMenu(1, obj); };
       div_Menu1.innerHTML = "set";

       var div_Menu2 = document.createElement("Div");
       div_Menu2.className = "divMenuItem";
       div_Menu2.onclick = function() { selectDivRightMenu(2, obj)};
       div_Menu2.innerHTML = "free";

       div_Menu.appendChild(div_Menu1);
       div_Menu.appendChild(div_Menu2);

       document.body.appendChild(div_Menu);
   }
   
   function removeDivRightMenu()
   {
       if (document.getElementById("div_RightMenu") != null) {
       
           element = document.getElementById("div_RightMenu");
           element.parentNode.removeChild(element);
       }
   }
   
   function selectDivRightMenu(param1, param2)
   {
       if (param1 == 1) {


           //
           removeDivRightMenu();
       }
       else if (param1 == 2) {

           //
            removeDivRightMenu();
       }
        
   }