WEB领域中,为实现上下文菜单,开发人员面临的主要问题是如何确定应该显示这个上下文菜单(Windows 中,右键单击;Mac 中,Ctrl+单击),
以及如何屏蔽与该操作相关联的默认上下文菜单。
解决方案:
contextmenu事件,用以表示何时应该显示上下文菜单,以便取消默认的上下文菜单而提供自定义的菜单。
contextmenu事件支持冒泡,可以通过为document指定一个事件处理程序,用以处理页面上所有此类事件。
html代码
1 2 316 174 5 6 Right click or Ctrl+click me to get a custom context menu. 7 Click anywhere esle to get the default context menu. 89
js代码
1 var EventUtil = { 2 3 addHandler: function(element, type, handler){ 4 if(element.addEventListener){ 5 element.addEventListener(type, handler, false); 6 }else if(element.attachEvent){ 7 element.attachEvent("on" + type, handler); 8 }else{ 9 element["on" + type] = handler;10 } 11 },12 13 getEvent: function(event){14 return event?event: window.event; 15 }, 16 17 getTarget: function(event){18 return event.target|| event.srcElement; 19 }, 20 21 preventDefault: function(event){22 if(event.preventDefault){23 event.preventDefault(); 24 }else{25 event.returnValue = false;26 }27 },28 29 removeHandler: function(event){30 if(element.removeEventListener){31 element.removeEventListener(type, handler, false);32 }33 else if(element.detachEvent)34 {35 element.detachEvent("on" + type, handler);36 }else{37 element["on" + type] = null;38 }39 },40 41 stopPropagation: function(event){42 if(event.stopPropagation){43 event.stopPropagation();44 }else{ 45 event.cancelBubble = true; 46 }47 },48 49 getCharCode: function(event){50 if(typeof event.charCode == "number"){51 return event.charCode;52 }else{53 return event.keyCode;54 }55 }56 }
1 EventUtil.addHandler(window, "load", function(event){ 2 3 var div = document.getElementById("myDiv"); 4 5 EventUtil.addHandler(div, "contexmenu", function(event){ 6 event = EventUtil.getEvent(event); 7 EventUtil.preventDefault(event); 8 9 var menu = document.getElementById("myMenu");10 menu.style.left = event.clientX + "px"; 11 menu.style.top = event.clientY + "px";12 menu.style.visibility = "visible"; 13 });14 15 EventUtil.addHandler(document, "click", function(event){16 document.getElementById("myMenu").style.visibility = "hidden";17 });18 })