鼠标右键兼容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 右键展现重写菜单 左键隐蔽
    原文作者:sgosky
    原文地址: https://segmentfault.com/a/1190000018334604
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞