我想添加一个自定义右键菜单到我的web应用程序。这可以在不使用任何预先构建的库的情况下完成吗?如果是这样,如何显示一个简单的自定义右键菜单,不使用第三方JavaScript库?

我的目标是像谷歌Docs做的东西。它允许用户右键单击并显示用户自己的菜单。

注意: 我想学习如何制作我自己的,而不是使用别人已经制作的东西,因为大多数时候,那些第三方库的功能都很臃肿,而我只想要我需要的功能,所以我希望它完全由我手工制作。


当前回答

一个简单的方法是使用onContextMenu返回一个JavaScript函数:

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

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

7:13进入的时候,回的是虚假。您将取消上下文菜单。

如果你仍然想显示上下文菜单,你可以删除返回false;线。

其他回答

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

您可以调整和修改这段代码,使上下文菜单看起来更美观、更高效。至于修改一个现有的上下文菜单,我不知道如何做到这一点…看看这把小提琴,有组织的观点。另外,试着点击我的上下文菜单中的项目。他们应该提醒你一些很棒的信息。如果它们不起作用,那就试试别的……复杂。

我知道这个问题已经有了答案,但我花了一些时间来解决第二个答案,以使本机上下文菜单消失,并在用户单击的地方显示出来。 超文本标记语言

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

试试这个:

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>

我使用类似于下面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;情况下

你可以用这段代码来做。 访问这里获得完整的自动边缘检测教程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();
 });
 });

`