美文网首页
js定制右键菜单

js定制右键菜单

作者: zhanggongzi | 来源:发表于2018-08-30 20:52 被阅读0次

    多话不说,直接上代码,该代码只做演示,写的不优雅···

    (function(){

    var _htm = [
    
      '<div id="document-menu" style="visibility:hidden;position:fixed;min-width:120px;background-color:#eee;border:1px solid #ccc;border-radius:5px;padding:10px;box-shadow:0 0 14px #777;z-index:10001;">',
    
      '<ul>',
    
      '<li><a href="http://www.qingqingjianji.com/article.html?aid=72">显示网页源代码</a></li>',
    
      '<li><a href="#">检查</a></li>',
    
      '</ul>',
    
      '</div>'
    
    ].join('');
    
    var div = document.createElement("div");
    
    div.innerHTML = _htm;
    
    if(!document.getElementById("document-menu")){
    
        document.body.appendChild(div);
    
        var sty = document.createElement("style");
    
        sty.type = "text/css";
    
        sty.innerHTML = "#document-menu ul li a{color: #333;text-decoration: none;}#document-menu ul li a:hover{color: blue;}";
    
        document.getElementsByTagName("head")[0].appendChild(sty);
    
    }
    
    var menuEle = document.getElementById("document-menu");
    
    document.oncontextmenu = function(e){
    
        var e = e || window.event;
    
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
    
        var x = e.clientX, y = e.clientY;
    
        var clientWidth = window.innerWidth || document.documentElement.clientWidth, clientHeight = window.innerHeight || document.documentElement.clientHeight;
    
        var divWidth = menuEle.offsetWidth, divHeight = menuEle.offsetHeight;
    
        //debugger
    
        if(x + divWidth > clientWidth){
    
            x = clientWidth - divWidth-20;
    
            if (x < 0) x = 0;
    
        }
    
        if(y + divHeight > clientHeight){
    
            y = clientHeight - divHeight-20;
    
            if (y < 0) y = 0;
    
        }
    
        menuEle.style.left = x+"px";
    
        menuEle.style.top = y+"px";
    
        menuEle.style.visibility = "visible";
    
    }
    
    document.onclick = function(e){
    
        var e = e || window.event;
    
        if(e.button != 2){
    
            menuEle.style.visibility = "hidden";
    
        }
    
    }
    

    })()

    相关文章

      网友评论

          本文标题:js定制右键菜单

          本文链接:https://www.haomeiwen.com/subject/kvadwftx.html