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

后端 未结 19 1218
广开言路
广开言路 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:17

    Pure JS and css solution for a truly dynamic right click context menu, albeit based on predefined naming conventions for the elements id, links etc. jsfiddle and the code you could copy paste into a single static html page :

    <html>
    
    <head>
      <style>
        .cls-context-menu-link {
          display: block;
          padding: 20px;
          background: #ECECEC;
        }
        
        .cls-context-menu {
          position: absolute;
          display: none;
        }
        
        .cls-context-menu ul,
        #context-menu li {
          list-style: none;
          margin: 0;
          padding: 0;
          background: white;
        }
        
        .cls-context-menu {
          border: solid 1px #CCC;
        }
        
        .cls-context-menu li {
          border-bottom: solid 1px #CCC;
        }
        
        .cls-context-menu li:last-child {
          border: none;
        }
        
        .cls-context-menu li a {
          display: block;
          padding: 5px 10px;
          text-decoration: none;
          color: blue;
        }
        
        .cls-context-menu li a:hover {
          background: blue;
          color: #FFF;
        }
      </style>
    </head>
    
    <body>
    
      <!-- those are the links which should present the dynamic context menu -->
      <a id="link-1" href="#" class="cls-context-menu-link">right click link-01</a>
      <a id="link-2" href="#" class="cls-context-menu-link">right click link-02</a>
    
      <!-- this is the context menu -->
      <!-- note the string to=0 where the 0 is the digit to be replaced -->
      <div id="div-context-menu" class="cls-context-menu">
        <ul>
          <li><a href="#to=0">link-to=0 -item-1 </a></li>
          <li><a href="#to=0">link-to=0 -item-2 </a></li>
          <li><a href="#to=0">link-to=0 -item-3 </a></li>
        </ul>
      </div>
    
      <script>
        var rgtClickContextMenu = document.getElementById('div-context-menu');
    
        /** close the right click context menu on click anywhere else in the page*/
        document.onclick = function(e) {
          rgtClickContextMenu.style.display = 'none';
        }
    
        /**
         present the right click context menu ONLY for the elements having the right class
         by replacing the 0 or any digit after the "to-" string with the element id , which
         triggered the event
        */
        document.oncontextmenu = function(e) {
          //alert(e.target.id)
          var elmnt = e.target
          if (elmnt.className.startsWith("cls-context-menu")) {
            e.preventDefault();
            var eid = elmnt.id.replace(/link-/, "")
            rgtClickContextMenu.style.left = e.pageX + 'px'
            rgtClickContextMenu.style.top = e.pageY + 'px'
            rgtClickContextMenu.style.display = 'block'
            var toRepl = "to=" + eid.toString()
            rgtClickContextMenu.innerHTML = rgtClickContextMenu.innerHTML.replace(/to=\d+/g, toRepl)
            //alert(rgtClickContextMenu.innerHTML.toString())
          }
        }
      </script>
    </body>
    
    </html>

    0 讨论(0)
  • 2020-11-22 16:19

    Answering your question - use contextmenu event, like below:

    if (document.addEventListener) {
      document.addEventListener('contextmenu', function(e) {
        alert("You've tried to open context menu"); //here you draw your own menu
        e.preventDefault();
      }, false);
    } else {
      document.attachEvent('oncontextmenu', function() {
        alert("You've tried to open context menu");
        window.event.returnValue = false;
      });
    }
    <body>
      Lorem ipsum...
    </body>

    But you should ask yourself, do you really want to overwrite default right-click behavior - it depends on application that you're developing.


    JSFIDDLE

    0 讨论(0)
  • 2020-11-22 16:19

    You can do it with this code. visit here for full tutorial with automatic edge detection http://www.voidtricks.com/custom-right-click-context-menu/

    $(document).ready(function () {
     $("html").on("contextmenu",function(e){
            //prevent default context menu for right click
            e.preventDefault();
    
            var menu = $(".menu"); 
    
            //hide menu if already shown
            menu.hide(); 
    
            //get x and y values of the click event
            var pageX = e.pageX;
            var pageY = e.pageY;
    
            //position menu div near mouse cliked area
            menu.css({top: pageY , left: pageX});
    
            var mwidth = menu.width();
            var mheight = menu.height();
            var screenWidth = $(window).width();
            var screenHeight = $(window).height();
    
            //if window is scrolled
            var scrTop = $(window).scrollTop();
    
            //if the menu is close to right edge of the window
            if(pageX+mwidth > screenWidth){
            menu.css({left:pageX-mwidth});
            }
    
            //if the menu is close to bottom edge of the window
            if(pageY+mheight > screenHeight+scrTop){
            menu.css({top:pageY-mheight});
            }
    
            //finally show the menu
            menu.show();
     }); 
    
     $("html").on("click", function(){
     $(".menu").hide();
     });
     });
    

    `

    0 讨论(0)
  • 2020-11-22 16:23

    A simple way you could do it is use onContextMenu to return a JavaScript function:

    <input type="button" value="Example" onContextMenu="return RightClickFunction();">
    
    <script>
     function RightClickFunction() {
      // Enter your code here;
      return false;
     }
    </script>
    

    And by entering return false; you will cancel out the context menu.

    if you still want to display the context menu you can just remove the return false; line.

    0 讨论(0)
  • 2020-11-22 16:25

    You could try simply blocking the context menu by adding the following to your body tag:

    <body oncontextmenu="return false;">
    

    This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).

    P.S. you can add this to any tag you want to disable the context menu on

    for example:

    <div class="mydiv" oncontextmenu="return false;">
    

    Will disable the context menu in that particular div only

    0 讨论(0)
  • 2020-11-22 16:27

    I know this has already been answered, but I spent some time wrestling with the second answer to get the native context menu to disappear and have it show up where the user clicked.
    HTML

    <body>
        <div id="test1">
            <a href="www.google.com" class="test">Google</a>
            <a href="www.google.com" class="test">Link 2</a>
            <a href="www.google.com" class="test">Link 3</a>
            <a href="www.google.com" class="test">Link 4</a>
        </div>
    
        <!-- initially hidden right-click menu -->
        <div class="hide" id="rmenu">
            <ul>
                <li class="White">White</li>
                <li>Green</li>
                <li>Yellow</li>
                <li>Orange</li>
                <li>Red</li>
                <li>Blue</li>
            </ul>
        </div>
    </body>
    

    CSS

    .hide {
      display: none;
    }
    
    #rmenu {
      border: 1px solid black;
      background-color: white;
    }
    
    #rmenu ul {
      padding: 0;
      list-style: none;
    }
    #rmenu li
    {
      list-style: none;
      padding-left: 5px;
      padding-right: 5px;
    }
    

    JavaScript

    if (document.getElementById('test1').addEventListener) {
        document.getElementById('test1').addEventListener('contextmenu', function(e) {
                $("#rmenu").toggleClass("hide");
                $("#rmenu").css(
                  {
                    position: "absolute",
                    top: e.pageY,
                    left: e.pageX
                  }
                );
                e.preventDefault();
         }, false);
    }
    
    // this is from another SO post...  
    $(document).bind("click", function(event) {
      document.getElementById("rmenu").className = "hide";
    });
    

    CodePen Example

    0 讨论(0)
提交回复
热议问题