代码之家  ›  专栏  ›  技术社区  ›  Franki1986

javascript:如何检查是否在上下文菜单new tab上单击了链接

  •  0
  • Franki1986  · 技术社区  · 7 年前

    是否可以检查是否单击链接以在新窗口中打开? 我的意思是Ctrl或Shift键按下是清楚的,你可以处理这个事件,但是浏览器中的右键上下文菜单呢?在这里,您可以单击在另一个窗口中打开的上下文菜单项。

    打开上下文菜单时触发jquery context()方法:

    $("a").contextmenu(function() {
      alert("context");
    });
    
    $("a").click(
        if (evnt.ctrlKey || evnt.shiftKey || evnt.metaKey || 
            (evnt.button && evnt.button == 1)){
            alert("link clicked");
        }
    );
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Alex    7 年前

    我想出了这个解决方案,这是非常老套和DIY,但应该做的伎俩。

    诀窍是使用以下命令创建自己的上下文菜单 jQuery 插件:

    https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.js https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.css https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.ui.position.js

    这不会在上执行 SO 我建议在jsfiddle上运行它: JSFiddle


    $(function() {
      $.contextMenu({
        selector: '.context-menu-one',
        callback: function(key, options) {
    
          var m = "clicked: " + key;
          window.console && console.log(m);
    
          switch (key) {
            case "open_new_window":
              console.log($(this));
              //var win = window.open($(this)[0].href, '_blank');
              window.open($(this)[0].href,'_blank');
              //win.focus();
              break;
            case "cut":
              break;
          }
        },
        items: {
          "open_new_window": {
            name: "Open link in new tab",
            icon: "edit"
          },
          "cut": {
            name: "Cut",
            icon: "cut"
          }
        }
      });
    });
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script src="https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.ui.position.js"></script>
    <link href="https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.css" rel="stylesheet"/>
    <script src="https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.js"></script>
    
    
    <a class="context-menu-one" href="https://www.google.com">Google</a><br>
    <a class="context-menu-one" href="https://www.bing.com">Bing</a><br>
    <a class="context-menu-one" href="https://www.yahoo.com">Yahoo</a><br>
    <a class="context-menu-one" href="https://www.facebook.com">Facebook</a><br>