简体   繁体   English

如何命令+单击以在新选项卡中打开 url 并在 JavaScript 中切换到它?

[英]How to command+click to open url in new tab and switch to it in JavaScript?

There is a div element.有一个div元素。 The goal is to detect command+click to open some URL in the new tab and switch to the new tab .目标是检测命令+单击以在新选项卡中打开一些 URL并切换到新选项卡 I've already done the detection and open.我已经做了检测并打开了。

The problem is: I use the same method to open URL: simply use window.open() .问题是:我用同样的方法打开 URL :只需使用window.open() When I press command and click, it will not switch to the new tab .当我按下命令并单击时,它不会切换到新选项卡 When I just click, it will switch.当我单击时,它会切换。

<div
  onClick={(event) => {
    if (event.metaKey || event.ctrlKey) {
      // will not switch, but why?
      openLink('https://stackoverflow.com/');
    }
  }}
>
  command Click or ctrl Click
</div>

<div
  onClick={(event) => {
    // will switch
    openLink('https://stackoverflow.com/');
  }}
>
  just click
</div>     

So I am wondering how to make command+click to open a new tab and switch to it?所以我想知道如何让命令+单击打开一个新选项卡并切换到它? Thanks for your help.谢谢你的帮助。

Here is a minimal code snippet on CodeSandbox .这是CodeSandbox上的最小代码片段。

Problem sovled.问题解决了。 I add setTimeout to it and it will switch.我将setTimeout添加到它,它会切换。 However, I still do not know why...但是,我仍然不知道为什么......

<div onClick={(event) => {
  if (event.metaKey || event.ctrlKey) {
    // it works, but why?
     setTimeout(() => openLink("https://stackoverflow.com/"));
  }
}}>
  command Click or ctrl Click
</div>

Try using event.ctrlKey , it will return a boolean that indicates if ctrl is pressed or not尝试使用event.ctrlKey ,它将返回一个 boolean 指示是否按下 ctrl

<div onClick={(event) => {
      if (event.metaKey || event.ctrlKey) {
        // will not switch, but why?
        openLink("https://stackoverflow.com/");
      }
    }}
  >
    command Click or ctrl Click
</div>

This will work but for both simple click and cmd+click.这将有效,但对于简单的单击和 cmd+单击。

<div onClick={()=> window.open("someLink", "_blank")}>text</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM