用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();
       }
        
   }

你可能感兴趣的:(用javascript 实现网页鼠标右键弹出菜单功能)