How to add a custom right-click menu to a webpage?

后端 未结 19 1601
广开言路
广开言路 2020-11-22 15:54

I want to add a custom right-click menu to my web application. Can this be done without using any pre-built libraries? If so, how to display a simple custom right-click menu

19条回答
  •  醉话见心
    2020-11-22 16:30

    A combination of some nice CSS and some non-standard html tags with no external libraries can give a nice result (JSFiddle)

    HTML

    
        
            
            
            
        
        
            
            
            
        
    
    

    Note: the menu tag does not exist, I'm making it up (you can use anything)

    CSS

    #ctxMenu{
        display:none;
        z-index:100;
    }
    menu {
        position:absolute;
        display:block;
        left:0px;
        top:0px;
        height:20px;
        width:20px;
        padding:0;
        margin:0;
        border:1px solid;
        background-color:white;
        font-weight:normal;
        white-space:nowrap;
    }
    menu:hover{
        background-color:#eef;
        font-weight:bold;
    }
    menu:hover > menu{
        display:block;
    }
    menu > menu{
        display:none;
        position:relative;
        top:-20px;
        left:100%;
        width:55px;
    }
    menu[title]:before{
        content:attr(title);
    }
    menu:not([title]):before{
        content:"\2630";
    }
    

    The JavaScript is just for this example, I personally remove it for persistent menus on windows

    var notepad = document.getElementById("notepad");
    notepad.addEventListener("contextmenu",function(event){
        event.preventDefault();
        var ctxMenu = document.getElementById("ctxMenu");
        ctxMenu.style.display = "block";
        ctxMenu.style.left = (event.pageX - 10)+"px";
        ctxMenu.style.top = (event.pageY - 10)+"px";
    },false);
    notepad.addEventListener("click",function(event){
        var ctxMenu = document.getElementById("ctxMenu");
        ctxMenu.style.display = "";
        ctxMenu.style.left = "";
        ctxMenu.style.top = "";
    },false);
    

    Also note, you can potentially modify menu > menu{left:100%;} to menu > menu{right:100%;} for a menu that expands from right to left. You would need to add a margin or something somewhere though

提交回复
热议问题