屏蔽鼠标右键单击出现的默认上下文菜单,提供自定义菜单
<div id="myDiv" >hhhhhhhhhhhhh</div>
<div id="myMenu" style="visibility: hidden;background-color:red;position: absolute">
自定义菜单
</div>
<script src="EventUtil.js"></script>//此js文件见上文
<script>
//load事件
EventUtil.addHandler(window,"load",function (event) {
var myDiv = document.getElementById('myDiv');
EventUtil.addHandler(myDiv,"contextmenu",function (event) {
var myMenu = document.getElementById('myMenu');
console.log(event)
event = EventUtil.getEvent(event);
EventUtil.preventDefault(event);
myMenu.style.visibility = 'visible';
myMenu.style.left = event.clientX + 'px';
myMenu.style.top = event.clientY + 'px';
});
EventUtil.addHandler(document,"click",function (event) {
document.getElementById("myMenu").style.visibility = "hidden"
})
});
//兼容跨浏览器的事件对象
var EventUtil = {
addHandler: function (element,type,handler) {
if(element.addEventListener){
element.addEventListener(type,handler,false)
}else if(element.attachEvent){
element.attachEvent("on"+type,handler);
}else{
element["on"+type] = handler;
}
},
getEvent: function (event) {
return event ? event : window.event;
},
getTarget: function (event) {
return event.target || event.srcElement;
},
preventDefault: function (event) {
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
}
},
removeHandler: function (element,type,handler) {
if(element.removeEventListener){
element.removeEventListener(type,handler,false)
}else if(element.detachEvent){
element.detachEvent("on"+type,handler);
}else{
element["on"+type] = null;
}
},
stopPropagation: function (event) {
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble = true;
}
},
getCharCode: function (event) {
if(typeof event.charCode == "number"){
return event.charCode;
}else{
return event.keyCode;
}
}
};