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

右键单击并选择“打开…”之一后,从上下文菜单中替换href link

  •  0
  • Michal_Szulc  · 技术社区  · 6 年前

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   Michal_Szulc    6 年前

    事实上,我找到了一个更好/更简单的方法来实现它。replaceLink()负责在此处替换centextmenu链接:

    <html>
       <head>
          <meta charset="utf-8"/>
       </head>
       <body>
          <a href="https://majkesz.pl" id="lol" oncontextmenu="replaceLink(event);">majkesz.pl</a><br>
          <script>
         document.getElementById("lol").onclick = function(event) {
            event.preventDefault();
            window.location.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
            return false;
            };
    
    
         function replaceLink(e) {
         e.target.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
    
         }
          </script>
       </body>
    </html>
    

    不幸的是,上述解决方案不适用于FF和更新版本的chrome鼠标中键。而是使用通用:

    <html>
       <head>
          <meta charset="utf-8"/>
       </head>
       <body>
          <a href="https://majkesz.pl" onmousedown="replaceLink(event)" oncontextmenu="replaceLink(event);">majkesz.pl</a><br>
          <script>
         function replaceLink(e) {
         e.target.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
    
         }
          </script>
       </body>
    </html>
    
        2
  •  0
  •   Haris Bouchlis Rohit Baila    6 年前

    http://ignitersworld.com/lab/contextMenu.html .

    编辑:你可以试试这个,虽然有点老套。

    <html>
    <head>
    </head>
    <body>
    <a href="http://www.google.com">Google</a>
    <script>
    
        // get all anchor elements
        var anchors = document.getElementsByTagName("a");
    
        for(var i=0; i<anchors.length; i++){
            var el = anchors[i];
    
            // add event listener on each anchor element
            el.addEventListener('contextmenu', function(ev) {
    
                // get the original href value of the element
                var originalTarget = el.href;
    
                // change it to what you want to go to
                el.href = 'http://www.amazon.com';
    
                // asynchonously change it back to the original
                setTimeout(function(){
                    el.href = originalTarget;
                },1);
            }, false);
        }
    
    </script>
    </body>
    </html>