[英]jQuery/JavaScript - Allow CTRL + Click to open link in new tab
Is there a way in jQuery or JavaScript to enable the user to CTRL + Click a link to open a link in a new tab like <a href="">example</a>
element?在 jQuery 或 JavaScript 中是否有一种方法可以让用户按 CTRL + 单击链接以在新选项卡(例如
<a href="">example</a>
元素)中打开链接?
Here is an example of what I am talking about:-这是我正在谈论的一个例子:-
jQuery('#some-link').bind('click', function() {
window.location = 'http://someurl.com';
});
If you hold CTRL and click the 'some-link' element, it just opens the page within the current page when using the above code, any ideas on how do this?如果您按住 CTRL 键并单击“some-link”元素,则在使用上述代码时它只会在当前页面内打开页面,有关如何执行此操作的任何想法?
Check to see if the Ctrl
key is pressed, and open the link using window.open
.检查是否按下了
Ctrl
键,然后使用window.open
打开链接。 The link may not open in a new tab though.不过,该链接可能无法在新标签页中打开。 See the discussion here .
请参阅此处的讨论。
jQuery('#some-link').bind('click', function(e) {
e.preventDefault();
if (e.ctrlKey){
window.open('http://someurl.com','_blank')
}
});
In case anyone wants to disable page navigation on regular click, to make an ajax call or something, but still wants to keep the default ctrl+click and right-click and middle-click(mouse scroll button) , that is the way:如果有人想在常规点击时禁用页面导航,进行 ajax 调用或其他操作,但仍想保留默认的 ctrl+click 和 right-click 和 middle-click(mouse scroll button) ,那就是方法:
$('#link').bind('click', function(e) { if (!e.ctrlKey && e.which != 2 && e.which != 3) { e.preventDefault(); // some logic: $('#box').append('<br>').append($('<a>').html('not paging but doing something! Now try with CTRL')); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box"> <a id="link" href="http://stackoverflow.com/questions/26823884/">this question</a> </div>
JQuery documentation says: JQuery文档说:
event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right.
event.which 也标准化按钮按下(mousedown 和 mouseupevents),左键报告 1,中间报告 2,右报告 3。 Use event.which instead of event.button.
使用 event.which 而不是 event.button。
On Macintosh keyboards, this is the ⌘ Command key.在 Macintosh 键盘上,这是 ⌘ 命令键。 On Windows keyboards, this is the Windows key (⊞ Windows).
在 Windows 键盘上,这是 Windows 键 (⊞ Windows)。
For more see this page:有关更多信息,请参阅此页面:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.