使用contextmenu事件控制右键菜单

在此单击鼠标右键显示自定义菜单
此区域屏蔽鼠标右键菜单
window.onload = function(e) {
    var div1 = document.getElementById('div1'),
        div2 = document.getElementById('div2'),
        menu = document.getElementById('menu');

    addHandler(div1, 'contextmenu', function(e){
        e = e || window.event;
        preventDefault(e);

        menu.style.left = e.clientX+'px';
        menu.style.top = e.clientY+'px';
        menu.style.display = 'block';
    });

    addHandler(div2, 'contextmenu', function(e){
        e = e || window.event;
        preventDefault(e);
    });

    addHandler(menu, 'contextmenu', function(e){
        e = e || window.event;
        preventDefault(e);
    });

    addHandler(document, 'mousedown', function(e){
        e = e || window.event;
        var obj = e.srcElement?e.srcElement:e.target;
        if(isChild(menu, obj)){
            return false;
        }
        menu.style.display = 'none';
    });
};

function isChild(parent, child) {
    while (child != null) {
        if (child == parent) {
            return true;
        }
        child = child.parentNode;
    }
    return false;
}

function addHandler(element, type, handler) {
    if(element.addEventListener){
        element.addEventListener(type,handler,false);
    }else{
        element.attachEvent('on'+type,handler);
    }
}

function preventDefault(e){
    e = e || window.event;
    if(e.preventDefault){
        e.preventDefault();
    }else{
        e.returnValue = false;
    }
}