鼠标右键兼容MAC版火狐浏览器

oncontextmenu事件 在MAC版火狐浏览器下表现差异

谷歌和其它浏览器
//css
    *{margin:0;padding:0;}
    #right-menu{position:absolute;width:150px;visibility:hidden;border:1px solid #bababa;box-shadow: 1px 1px 2px #8e8e8e;}
    #right-menu li{list-style:none;text-indent:1em;}
    #right-menu li a{display:block;height:30px;line-height:30px;text-decoration:none;color:#666;font-size: 12px;}
    #right-menu li a:hover{background:#ebebeb;color:black;}

//html
<div id="right-menu">
    <ul>
        <li><a href="#">打印</a></li>
        <li><a href="#">复制</a></li>
    </ul>
</div>

//js
document.oncontextmenu = function(e){
    if(window.event) e = window.event;
    var mymenu = document.getElementById("right-menu");
    mymenu.style.visibility = "visible";
    mymenu.style.left = e.clientX + 5 +"px";
    mymenu.style.top = e.clientY + 5 + "px";
    return false;//阻止右键系统默认的弹出框
};
document.onclick = function(){
    var mymenu = document.getElementById("right-menu");
    mymenu.style.visibility = "hidden"; 
}
//除了火狐,oncontextmenu在其他浏览器上的交互 右键mouseup 执行事件
//火狐是mousedown的时候执行 抬起消失
兼容写法
document.oncontextmenu = function(e){
    return false;
};
document.onmouseup=function(e) {
    var mymenu = document.getElementById("right-menu");
    if (!e) e=window.event;
    if (e.button==0) {
        mymenu.style.visibility = "hidden"; 
    }
    if (e.button==2) {
        mymenu.style.visibility = "visible";
        mymenu.style.left = e.clientX + 5 +"px";
        mymenu.style.top = e.clientY + 5 + "px";
    }
}

//思路 
1.阻止默认事件
2.mouseup 右键展示重写菜单 左键隐藏

相关推荐