簡體   English   中英

如何在網頁中添加自定義右鍵菜單?

[英]How to add a custom right-click menu to a webpage?

我想向我的 web 應用程序添加自定義右鍵菜單。 這可以在不使用任何預建庫的情況下完成嗎? 如果是這樣,如何顯示一個不使用第三方 JavaScript 庫的簡單自定義右鍵菜單?

我的目標是類似於 Google Docs 所做的事情。 它允許用戶右鍵單擊並向用戶顯示他們自己的菜單。

注意:我想學習如何制作自己的東西而不是使用別人已經制作的東西,因為大多數時候,那些第 3 方庫的功能很臃腫,而我只想要我需要的功能,所以我希望它完全由手工制作我。

回答你的問題 - 使用contextmenu事件,如下所示:

 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> 

但是你應該問自己,你真的想要覆蓋默認的右鍵單擊行為 - 這取決於你正在開發的應用程序。


的jsfiddle

對我來說非常有用。 為了像我這樣的人,期待繪制菜單,我把這里用來制作右鍵菜單的代碼放在這里:

 $(document).ready(function() { if ($("#test").addEventListener) { $("#test").addEventListener('contextmenu', function(e) { alert("You've tried to open context menu"); //here you draw your own menu e.preventDefault(); }, false); } else { //document.getElementById("test").attachEvent('oncontextmenu', function() { //$(".test").bind('contextmenu', function() { $('body').on('contextmenu', 'a.test', function() { //alert("contextmenu"+event); document.getElementById("rmenu").className = "show"; document.getElementById("rmenu").style.top = mouseY(event) + 'px'; document.getElementById("rmenu").style.left = mouseX(event) + 'px'; window.event.returnValue = false; }); } }); // this is from another SO post... $(document).bind("click", function(event) { document.getElementById("rmenu").className = "hide"; }); function mouseX(evt) { if (evt.pageX) { return evt.pageX; } else if (evt.clientX) { return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); } else { return null; } } function mouseY(evt) { if (evt.pageY) { return evt.pageY; } else if (evt.clientY) { return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); } else { return null; } } 
 .show { z-index: 1000; position: absolute; background-color: #C0C0C0; border: 1px solid blue; padding: 2px; display: block; margin: 0; list-style-type: none; list-style: none; } .hide { display: none; } .show li { list-style: none; } .show a { border: 0 !important; text-decoration: none; } .show a:hover { text-decoration: underline !important; } 
 <!-- jQuery should be at least version 1.7 --> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="contextmenu.js"></script> <link rel="stylesheet" href="contextmenu.css" /> <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> <a href="http://www.google.com">Google</a> </li> <li> <a href="http://localhost:8080/login">Localhost</a> </li> <li> <a href="C:\\">C</a> </li> </ul> </div> 

一些不錯的CSS和一些沒有外部庫的非標准html標簽的組合可以提供一個很好的結果(JSFiddle)

HTML

<menu id="ctxMenu">
    <menu title="File">
        <menu title="Save"></menu>
        <menu title="Save As"></menu>
        <menu title="Open"></menu>
    </menu>
    <menu title="Edit">
        <menu title="Cut"></menu>
        <menu title="Copy"></menu>
        <menu title="Paste"></menu>
    </menu>
</menu>

注意:菜單標簽不存在,我正在編寫(你可以使用任何東西)

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";
}

JavaScript僅用於此示例,我個人刪除了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);

另請注意,您可以修改menu > menu{left:100%;}menu > menu{right:100%;}以獲得從右向左擴展的菜單。 您需要在某處添加邊距或某些內容

最簡單的啟動 function,在 cursor position 創建一個上下文菜單,它會在鼠標離開時自行銷毀。

 oncontextmenu = (e) => { e.preventDefault() let menu = document.createElement("div") menu.id = "ctxmenu" menu.style = `top:${e.pageY-10}px;left:${e.pageX-40}px` menu.onmouseleave = () => ctxmenu.outerHTML = '' menu.innerHTML = "<p>Option1</p><p>Option2</p><p>Option3</p><p>Option4</p><p onclick='alert(`Thank you.`)'>Upvote</p>" document.body.appendChild(menu) }
 #ctxmenu { position: fixed; background: ghostwhite; color: black; cursor: pointer; border: 1px black solid } #ctxmenu > p { padding: 0 1rem; margin: 0 } #ctxmenu > p:hover { background: black; color: ghostwhite }

您可以嘗試通過在body標簽中添加以下內容來阻止上下文菜單:

<body oncontextmenu="return false;">

這將阻止對上下文菜單的所有訪問(不僅來自鼠標右鍵,還來自鍵盤)。

PS你可以將它添加到你要禁用上下文菜單的任何標簽上

例如:

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

將僅禁用該特定div中的上下文菜單

根據這里和其他'流程的答案,我制作了一個看起來像谷歌Chrome的版本,css3過渡。 JS小提琴

讓我們開始說話,因為我們在這個頁面上面有js,我們可以擔心css和布局。 我們將使用的布局是帶有<img>元素的<a>元素或字體awesome圖標( <i class="fa fa-flag"></i> )和<span>以顯示鍵盤快捷鍵。 所以這是結構:

<a href="#" onclick="doSomething()">
  <img src="path/to/image.gif" />
  This is a menu option
  <span>Ctrl + K</span>
</a>

我們將這些放在div中並在右鍵單擊時顯示div。 讓我們像在Google Chrome中一樣設計它們,好嗎?

#menu a {
  display: block;
  color: #555;
  text-decoration: no[...]

現在我們將從接受的答案中添加代碼,並獲取光標的X和Y值。 為此,我們將使用e.clientXe.clientY 我們正在使用客戶端,因此必須修復菜單div。

var i = document.getElementById("menu").style;
if (document.addEventListener) {
  document.addEventListener('contextmenu', function(e) {
    var posX = e.clientX;
    var posY = e.client[...]

就是這樣! 只需添加css轉換即可淡入淡出,完成!

 var i = document.getElementById("menu").style; if (document.addEventListener) { document.addEventListener('contextmenu', function(e) { var posX = e.clientX; var posY = e.clientY; menu(posX, posY); e.preventDefault(); }, false); document.addEventListener('click', function(e) { i.opacity = "0"; setTimeout(function() { i.visibility = "hidden"; }, 501); }, false); } else { document.attachEvent('oncontextmenu', function(e) { var posX = e.clientX; var posY = e.clientY; menu(posX, posY); e.preventDefault(); }); document.attachEvent('onclick', function(e) { i.opacity = "0"; setTimeout(function() { i.visibility = "hidden"; }, 501); }); } function menu(x, y) { i.top = y + "px"; i.left = x + "px"; i.visibility = "visible"; i.opacity = "1"; } 
 body { background: white; font-family: sans-serif; color: #5e5e5e; } #menu { visibility: hidden; opacity: 0; position: fixed; background: #fff; color: #555; font-family: sans-serif; font-size: 11px; -webkit-transition: opacity .5s ease-in-out; -moz-transition: opacity .5s ease-in-out; -ms-transition: opacity .5s ease-in-out; -o-transition: opacity .5s ease-in-out; transition: opacity .5s ease-in-out; -webkit-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1); -moz-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1); box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1); padding: 0px; border: 1px solid #C6C6C6; } #menu a { display: block; color: #555; text-decoration: none; padding: 6px 8px 6px 30px; width: 250px; position: relative; } #menu a img, #menu a i.fa { height: 20px; font-size: 17px; width: 20px; position: absolute; left: 5px; top: 2px; } #menu a span { color: #BCB1B3; float: right; } #menu a:hover { color: #fff; background: #3879D9; } #menu hr { border: 1px solid #EBEBEB; border-bottom: 0; } 
 <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/> <h2>CSS3 and JAVASCRIPT custom menu.</h2> <em>Stephan Stanisic | Lisence free</em> <p>Right-click anywhere on this page to open the custom menu. Styled like the Google Chrome contextmenu. And yes, you can use <i class="fa fa-flag"></i>font-awesome</p> <p style="font-size: small"> <b>Lisence</b> <br /> "THE PIZZA-WARE LICENSE" (Revision 42): <br /> You can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a Pizza in return. <br /> <a style="font-size:xx-small" href="https://github.com/KLVN/UrbanDictionary_API#license">https://github.com/KLVN/UrbanDictionary_API#license</a> </p> <br /> <br /> <small>(The white body background is just because I hate the light blue editor background on the result on jsfiddle)</small> <div id="menu"> <a href="#"> <img src="http://puu.sh/nr60s/42df867bf3.png" /> AdBlock Plus <span>Ctrl + ?!</span> </a> <a href="#"> <img src="http://puu.sh/nr5Z6/4360098fc1.png" /> SNTX <span>Ctrl + ?!</span> </a> <hr /> <a href="#"> <i class="fa fa-fort-awesome"></i> Fort Awesome <span>Ctrl + ?!</span> </a> <a href="#"> <i class="fa fa-flag"></i> Font Awesome <span>Ctrl + ?!</span> </a> </div> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>

<title>Context menu - LabLogic.net</title>

</head>
<body>

<script language="javascript" type="text/javascript">

document.oncontextmenu=RightMouseDown;
document.onmousedown = mouseDown; 



function mouseDown(e) {
    if (e.which==3) {//righClick
        alert("Right-click menu goes here");
    }
}


function RightMouseDown() { return false; }

</script>

</body>
</html>

測試並在Opera 11.6,firefox 9.01,Internet Explorer 9和chrome 17中工作。您可以在javascript右鍵菜單中查看工作示例

嘗試這個:

 var cls = true; var ops; window.onload = function() { document.querySelector(".container").addEventListener("mouseenter", function() { cls = false; }); document.querySelector(".container").addEventListener("mouseleave", function() { cls = true; }); ops = document.querySelectorAll(".container td"); for (let i = 0; i < ops.length; i++) { ops[i].addEventListener("click", function() { document.querySelector(".position").style.display = "none"; }); } ops[0].addEventListener("click", function() { setTimeout(function() { /* YOUR FUNCTION */ alert("Alert 1;"), }; 50); }). ops[1],addEventListener("click"; function() { setTimeout(function() { /* YOUR FUNCTION */ alert("Alert 2,"); }; 50). }), ops[2];addEventListener("click", function() { setTimeout(function() { /* YOUR FUNCTION */ alert("Alert 3;"); }. 50), }); ops[3],addEventListener("click"; function() { setTimeout(function() { /* YOUR FUNCTION */ alert("Alert 4;"). }, 50); }), ops[4];addEventListener("click"; function() { setTimeout(function() { /* YOUR FUNCTION */ alert("Alert 5."), }. 50); }). } document;addEventListener("contextmenu". function() { var e = window.event. e.preventDefault(); document.querySelector(";container").style;padding = "0px". var x = e.clientX. var y = e.clientY. var docX = window.innerWidth || document.documentElement;clientWidth || document.body.clientWidth || document.body.offsetWidth. var docY = window.innerHeight || document.documentElement;clientHeight || document.body.clientHeight || document,body.offsetHeight; var border = parseInt(getComputedStyle(document.querySelector(".container"), null).getPropertyValue('border-width')); var objX = parseInt(getComputedStyle(document.querySelector(".container"), null).getPropertyValue('width')) + 2; var objY = parseInt(getComputedStyle(document;querySelector(";container"); null);getPropertyValue('height')) + 2. if (x + objX > docX) { let diff = (x + objX) - docX. x -= diff + border. } if (y + objY > docY) { let diff = (y + objY) - docY. y -= diff + border; } document.querySelector(".position").style.display = "block"; document.querySelector(".position").style.top = y + "px"; document;querySelector(".position"),style.left = x + "px". }). window.addEventListener("resize"; function() { document;querySelector(".position"),style.display = "none". }). document.addEventListener("click"; function() { if (cls) { document;querySelector(".position"),style.display = "none". } }). document.addEventListener("wheel"; function() { if (cls) { document;querySelector(";position").style.display = "none"; static = false; } });
 .position { position: absolute; width: 1px; height: 1px; z-index: 2; display: none; }.container { width: 220px; height: auto; border: 1px solid black; background: rgb(245, 243, 243); }.container p { height: 30px; font-size: 18px; font-family: arial; width: 99%; cursor: pointer; display: flex; justify-content: center; align-items: center; background: rgb(245, 243, 243); color: black; transition: 0.2s; }.container p:hover { background: lightblue; } td { font-family: arial; font-size: 20px; } td:hover { background: lightblue; transition: 0.2s; cursor: pointer; }
 <div class="position"> <div class="container" align="center"> <table style="text-align: left; width: 99%; margin-left: auto; margin-right: auto;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: middle; text-align: center;">Option 1<br> </td> </tr> <tr> <td style="vertical-align: middle; text-align: center;">Option 2<br> </td> </tr> <tr> <td style="vertical-align: middle; text-align: center;">Option 3<br> </td> </tr> <tr> <td style="vertical-align: middle; text-align: center;">Option 4<br> </td> </tr> <tr> <td style="vertical-align: middle; text-align: center;">Option 5<br> </td> </tr> </tbody> </table> </div> </div>

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示例

試試這個

$(function() {
var doubleClicked = false;
$(document).on("contextmenu", function (e) {
if(doubleClicked == false) {
e.preventDefault(); // To prevent the default context menu.
var windowHeight = $(window).height()/2;
var windowWidth = $(window).width()/2;
if(e.clientY > windowHeight && e.clientX <= windowWidth) {
  $("#contextMenuContainer").css("left", e.clientX);
  $("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
  $("#contextMenuContainer").css("right", "auto");
  $("#contextMenuContainer").css("top", "auto");
} else if(e.clientY > windowHeight && e.clientX > windowWidth) {
  $("#contextMenuContainer").css("right", $(window).width()-e.clientX);
  $("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
  $("#contextMenuContainer").css("left", "auto");
  $("#contextMenuContainer").css("top", "auto");
} else if(e.clientY <= windowHeight && e.clientX <= windowWidth) {
  $("#contextMenuContainer").css("left", e.clientX);
  $("#contextMenuContainer").css("top", e.clientY);
  $("#contextMenuContainer").css("right", "auto");
  $("#contextMenuContainer").css("bottom", "auto");
} else {
  $("#contextMenuContainer").css("right", $(window).width()-e.clientX);
  $("#contextMenuContainer").css("top", e.clientY);
  $("#contextMenuContainer").css("left", "auto");
  $("#contextMenuContainer").css("bottom", "auto");
}
 $("#contextMenuContainer").fadeIn(500, FocusContextOut());
  doubleClicked = true;
} else {
  e.preventDefault();
  doubleClicked = false;
  $("#contextMenuContainer").fadeOut(500);
}
});
function FocusContextOut() {
 $(document).on("click", function () {
   doubleClicked = false; 
   $("#contextMenuContainer").fadeOut(500);
   $(document).off("click");           
 });
}
});

http://jsfiddle.net/AkshayBandivadekar/zakn7​​Lwb/14/

這是一個非常好的教程,介紹如何使用完整的代碼示例構建自定義上下文菜單 (沒有JQuery和其他庫)。

您還可以在GitHub上找到他們的演示代碼

它們提供了詳細的逐步說明,您可以按照這些說明構建自己的右鍵單擊上下文菜單(包括html,css和javascript代碼),並通過提供完整的示例代碼在最后對其進行匯總。

您可以輕松跟進並根據自己的需要進行調整。 並且不需要JQuery或其他庫。

這是他們的示例菜單代碼的樣子:

<nav id="context-menu" class="context-menu">
    <ul class="context-menu__items">
      <li class="context-menu__item">
        <a href="#" class="context-menu__link" data-action="View"><i class="fa fa-eye"></i> View Task</a>
      </li>
      <li class="context-menu__item">
        <a href="#" class="context-menu__link" data-action="Edit"><i class="fa fa-edit"></i> Edit Task</a>
      </li>
      <li class="context-menu__item">
        <a href="#" class="context-menu__link" data-action="Delete"><i class="fa fa-times"></i> Delete Task</a>
      </li>
    </ul>
  </nav>

可以在codepen上找到工作示例(任務列表)

純JS和css解決方案,用於真正動態的右鍵單擊上下文菜單,雖然基於元素id,鏈接等的預定義命名約定.jsfiddle和您可以復制粘貼到單個靜態html頁面的代碼:

     <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>

您可以使用此代碼執行此操作。 訪問此處獲取有關自動邊緣檢測的完整教程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();
 });
 });

`

<script language="javascript" type="text/javascript">
  document.oncontextmenu = RightMouseDown; 
  document.onmousedown = mouseDown; 

  function mouseDown(e) {
    if (e.which==3) {//righClick
      alert("Right-click menu goes here");
    } 
  }

  function RightMouseDown() { 
    return false; 
  }
</script>
</body> 
</html>

一個簡單的方法就是使用onContextMenu來返回一個JavaScript函數:

<input type="button" value="Example" onContextMenu="return RightClickFunction();">

<script>
 function RightClickFunction() {
  // Enter your code here;
  return false;
 }
</script>

並通過輸入return false; 你將取消上下文菜單。

如果你仍想顯示上下文菜單,你可以刪除return false; 線。

經過測試並可在Opera 12.17,firefox 30,Internet Explorer 9和chrome 26.0.1410.64中使用

document.oncontextmenu =function( evt ){
        alert("OK?");
        return false;
        }

您應該記住是否要使用僅Firefox解決方案,如果要將其添加到整個文檔,則應將contextmenu="mymenu"添加到<html>標記而不是body標記。
你應該注意這一點。

<html>
<head>
<style>
.rightclick {
    /* YOUR CONTEXTMENU'S CSS */
    visibility: hidden;
    background-color: white;
    border: 1px solid grey;
    width: 200px;
    height: 300px;
}
</style>
</head>
<body>
  <div class="rightclick" id="ya">
    <p onclick="alert('choc-a-late')">I like chocolate</p><br><p onclick="awe-so-me">I AM AWESOME</p>
  </div>
  <p>Right click to get sweet results!</p>
</body>
<script>
    document.onclick = noClick;
    document.oncontextmenu = rightClick;
    function rightClick(e) {
        e = e || window.event;
        e.preventDefault();
        document.getElementById("ya").style.visibility = "visible";
        console.log("Context Menu v1.3.0 by IamGuest opened.");
   }
function noClick() {
    document.getElementById("ya").style.visibility = "hidden";
    console.log("Context Menu v1.3.0 by IamGuest closed.");
}
</script>
<!-- Coded by IamGuest. Thank you for using this code! -->
</html>

您可以調整和修改此代碼,以獲得更好看,更高效的上下文菜單。 至於修改現有的上下文菜單,我不知道該怎么做...從有組織的角度來看這個小提琴 另外,嘗試單擊我的上下文菜單中的項目。 他們應該提醒你一些很棒的消息。 如果它們不起作用,請嘗試更復雜的東西。

<script>
function fun(){
document.getElementById('menu').style.display="block";
}

</script>
<div id="menu" style="display: none"> menu items</div>

<body oncontextmenu="fun();return false;">

我在這里做什么

  1. 創建自己的自定義div菜單並設置位置:絕對和顯示:無以防萬一。
  2. 添加到要單擊oncontextmenu事件的頁面或元素。
  3. 使用return false取消默認瀏覽器操作。
  4. 用戶js調用自己的動作。

我使用類似於以下jsfiddle的東西

function onright(el, cb) {
    //disable right click
    document.body.oncontextmenu = 'return false';
    el.addEventListener('contextmenu', function (e) { e.preventDefault(); return false });
    el.addEventListener('mousedown', function (e) {
        e = e || window.event;
        if (~~(e.button) === 2) {
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
            return false;
        }
    });

    // then bind Your cb
    el.addEventListener('mousedown', function (e) {
        e = e || window.event;
        ~~(e.button) === 2 && cb.call(el, e);
    });
}

如果您定位較舊的IE瀏覽器,無論如何應該使用'attachEvent; 案件

對於那些尋找使用引導程序 5 和 jQuery 3 的自定義上下文菜單的非常簡單的自包含實現的人,這里是...

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <title>Custom Context Menu</title>
</head>
<style>
#context-menu {
  position: absolute;
  display: none;
}
</style>
<body>
    <div class="container-fluid p-5">
        <div class="row p-5">
            <div class="col-4">
                <span id="some-element" class="border border-2 border-primary p-5">Some element</span>
            </div>
        </div>
        <div id="context-menu" class="dropdown clearfix">
            <ul class="dropdown-menu" style="display:block;position:static;margin-bottom:5px;">
              <li><a class="dropdown-item" href="#" data-value="copy">Copy</a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item" href="#" data-value="select-all">Select All</a></li>
            </ul>
        </div>       
        <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
        <script>
            $('body').on('contextmenu', '#some-element', function(e) {
                $('#context-menu').css({
                    display: "block",
                    left: e.pageX,
                    top: e.pageY
                });
                return false;
            });
            $('html').click(function() {
                $('#context-menu').hide();
            });
            $("#context-menu li a").click(function(e){
                console.log('in context-menu item, value = ' + $(this).data('value'));
            });
        </script>
    </body>
</html>

改編自https://codepen.io/anirugu/pen/xjjxvG

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM