[英]How can I open webpage in new tab with javascript and middle click
I have a anchor inside a list item我在列表项中有一个锚点
<li>
<a href="page"></a>
<span>description</span>
<span>count</span>
</li>
Using javascript, whenever the list item is clicked, the window opens the anchor's href.使用 javascript,只要单击列表项,window 就会打开锚点的 href。
I want to let the browser know that when it middle clicks it can treat the list item the same as the anchor, and open in a new tab.我想让浏览器知道,当它单击鼠标中键时,它可以将列表项视为与锚点相同,并在新选项卡中打开。
I've looked around and seen that most people think this cannot be done, but I think my situation could be different.我环顾四周,看到大多数人认为这是不可能做到的,但我认为我的情况可能有所不同。 One way of looking at it would be not to explicitly tell the browser to open a new tab, rather tell the browser to do what is does when middle click is used.一种看待它的方法是不要明确告诉浏览器打开一个新选项卡,而是告诉浏览器执行使用中键单击时执行的操作。
What do you think?你怎么认为?
EDIT : Updated html for a more accurate description.编辑:更新 html 以获得更准确的描述。 The anchor is not the only element in the list锚点不是列表中的唯一元素
_blank wasn't working for me in Chrome V92. _blank 在 Chrome V92 中对我不起作用。 Instead - A workaround will be to create a "fake" <a tag that will work only for middle clicks, like this:相反 - 一种解决方法是创建一个“假” <a 标签,该标签仅适用于中间点击,如下所示:
<li> <a href="https://google.com" id="fake-link" > Only clicks with middle buttons will work </a> </li> <script> document.getElementById('fake-link').addEventListener("click",(e) => e.preventDefault()); </script>
You want the list item to function as a link. 您希望列表项充当链接。 The simplest, most reliable way to do this is to get rid of the JavaScript and apply CSS to make the link fill the list item. 最简单,最可靠的方法是摆脱JavaScript并应用CSS使链接填充列表项。 Then any click on the list item will hit the link first. 然后,在列表项上的任何单击都将首先单击链接。 Listamatic has many examples . Listamatic有很多例子 。
Ok nay sayers :), I've figured out how to do it. 好吧,反对者:),我想出了办法。
With JS/jQuery I can determine which button is pressed. 使用JS / jQuery,我可以确定按下了哪个按钮。 Using this I can change the target value on the anchor to "_blank" only when the middle button is pressed. 使用此方法,只有在按下中间按钮时,我才能将锚的目标值更改为“ _blank”。
Using jQuery 1.7 使用jQuery 1.7
$('ul').on('click', 'li', function(e){
if(e.which == 2){
var newWindow = $(this).find('a').attr('href');
window.open(newWindow, 'newWindow');
e.preventDefault();
}
});
That's it. 而已。 jQuery normalizes the event.button
to event.which
so you can reliably detect middle clicks. jQuery的规范了event.button
到event.which
这样你就可以可靠地检测中间点击。 Then just open a new window. 然后只需打开一个新窗口。 Granted, whether or not it ends up in a new tab or a new windows entirely rests on the users' browser preferences. 当然,它是否最终出现在新选项卡或新窗口中完全取决于用户的浏览器首选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.