如何在新窗口和新选项卡/窗口中用鼠标右键打开链接

How to open a link in a new window and also in a new tab/window with right click?

本文关键字:窗口 鼠标 右键 链接 新选项 新窗口 选项      更新时间:2023-09-26

我有一个帮助链接。如果用户单击它,它将打开一个具有固定宽度和高度的新窗口。它运行得很好,只是当我右键单击链接时,要么没有"在新选项卡中打开"选项(在IE中),要么我可以在新选项卡上打开,但指向一个空页面(chrome)。有人能帮我把它变成一个链接吗?默认情况下,它也会在一个新窗口(而不是选项卡)中打开?

<html>
    <head>
        <title>
        link
        </title>
        <script type="text/javascript">
        function activateHelpView(helpUri) {
            var WindowId = 'SomeWindowId';
            var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
            if (helpWindow) {
                (helpWindow).focus();
            }
        }
        </script>
    </head>
    <body>
        <a id='PortOrderPageLearnMoreLink' href='javascript:' title='Learn more' onclick='activateHelpView("http://stackoverflow.com/")'>Learn more</a>
    </body>
</html>

使用实际链接,而不是空的javascript:地址。onclick处理程序可以防止链接做任何"正常"的事情,但您将有一些东西可供右键单击使用。

target=_blank是一个强烈的提示,表明您希望在新窗口中打开页面,但无论是在窗口中还是在选项卡中,这都是页面无法控制的。

<script type="text/javascript">
  function activateHelpView(helpUri) {
    var WindowId = 'SomeWindowId';
    var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
    if (helpWindow) {
      (helpWindow).focus();
    }
  }
</script>
<a id='PortOrderPageLearnMoreLink' href='http://stackoverflow.com/' title='Learn more' onclick='activateHelpView(this.href); return false;' target='_blank'>Learn more</a>

处理所有这些的一种更现代的方法——特别是如果有多个帮助链接的话——是向所有这些链接添加一个类,然后运行一些JavaScript依次向每个链接添加点击处理程序。HTML保持干净(并且具有真实链接,如果禁用或未加载JavaScript,仍然可以工作)。

var helplinks = document.querySelectorAll('.helplink');
for (var i = 0; i < helplinks.length; ++i) {
  helplinks[i].addEventListener('click', activateHelpView);
}
function activateHelpView(event) {
  event.stopPropagation();     // don't let the click run its course
  event.preventDefault();
  var helpUri = this.href;     // "this" will be the link that was clicked
  var WindowId = 'SomeWindowId';
  var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
  if (helpWindow) {
    helpWindow.focus();
  }
}
<a id='PortOrderPageLearnMoreLink' 
   href='http://stackoverflow.com/' title='Learn more' 
   class='helplink' target='_blank'>Learn more</a>

StackOverflow代码段不允许使用其中的某些函数。可以在这里找到一个工作示例。