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

后端 未结 19 1559
广开言路
广开言路 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: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;
      });
    }
    
      Lorem ipsum...
    

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


    JSFIDDLE

提交回复
热议问题