372

Web アプリケーションにカスタムの右クリック メニューを追加したいと考えています。ビルド済みのライブラリを使用せずにこれを行うことはできますか? もしそうなら、サードパーティの JavaScript ライブラリを使用しないシンプルなカスタム右クリック メニューを表示するにはどうすればよいですか?

Google Docs のようなものを目指しています。ユーザーは右クリックして、ユーザー独自のメニューを表示できます。

注: ほとんどの場合、サードパーティのライブラリは機能で肥大化しているため、自分で作成する方法と誰かがすでに作成したものを使用する方法を学びたいのですが、必要な機能だけが必要なので、完全に手作りしたい自分。

4

20 に答える 20

298

質問への回答 -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

于 2011-02-05T19:59:26.580 に答える
75

私にとって非常に役に立ちました。メニューの描画を期待している私のような人々のために、右クリックメニューを作成するために使用したコードをここに置きます。

$(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="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.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>

于 2013-05-10T11:18:13.073 に答える
13
<!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 の右クリック メニューで動作サンプルを確認できます。

于 2012-03-06T02:23:16.590 に答える
7

これはすでに回答されていることは知っていますが、ネイティブのコンテキスト メニューを非表示にして、ユーザーがクリックした場所に表示するために、2 番目の回答と格闘しまし
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 の例

于 2016-11-10T19:32:37.170 に答える
5

これは、完全に機能するコード例 (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 にあります。

于 2016-10-04T06:56:36.647 に答える
3

このコードでそれを行うことができます。自動エッジ検出に関する完全なチュートリアルについては、こちらをご覧ください 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();
 });
 });

`

于 2015-10-20T15:44:25.113 に答える
1
<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>
于 2013-10-28T21:01:08.303 に答える
1
<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 メニューを作成し、場合によっては position: absolute と display:none を設定します。
  2. クリックされるページまたは要素に oncontextmenu イベントを追加します。
  3. return false を使用して、デフォルトのブラウザ アクションをキャンセルします。
  4. js を使用して独自のアクションを呼び出します。

于 2017-07-26T11:47:01.387 に答える
0

Firefox のみのソリューションを使用する場合は覚えておく必要があります。ドキュメント全体に追加する場合はcontextmenu="mymenu"<html>タグではなくタグに追加する必要がありますbody
これに注意する必要があります。

于 2014-10-10T17:45:04.137 に答える