且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测用户是否尝试在新标签中打开链接?

更新时间:2023-11-27 23:13:28

你可以检查 ctrlKey shiftKey metaKey 事件对象的属性。如果其中一个为true,则为key control,shift或meta(Apple命令)键正在举行,您应该允许默认链接操作继续。否则,您使用 preventDefault 来停止链接操作并使用javascript处理它。

You can examine the ctrlKey, shiftKey, and metaKey properties of the event object. If either is true, the key control, shift, or meta (Apple's command) key is being held and you should allow the default link action to proceed. Otherwise, you use preventDefault to stop the link action and handle it with javascript instead.

target =_ blank添加到您的锚标记中,因此默认链接行为是打开一个新标签。否则它将打开顶部当前页面(可能是desi红色)。

Add target="_blank" to your anchor markup, so the default link behavior is opening a new tab. Otherwise it will open on top of the current page (that may be desired).

这里是javascript,无论如何:

Here's the javascript, either way:

document.getElementById("mylink").onclick = function(evnt) {
    if (
        evnt.ctrlKey || 
        evnt.shiftKey || 
        evnt.metaKey || // apple
        (evnt.button && evnt.button == 1) // middle click, >IE9 + everyone else
    ){
        return;
    }
    evnt.preventDefault();

    alert("clicked");
    return false;
}

小提琴:http://jsfiddle.net/6byrt0wu/

文档

  • MDN Events - https://developer.mozilla.org/en-US/docs/Web/API/Event
  • Event.ctrlKey - https://developer.mozilla.org/en-US/docs/Web/API/event.ctrlKey
  • Event.shiftKey - https://developer.mozilla.org/en-US/docs/Web/API/event.shiftKey
  • Event.metaKey - https://developer.mozilla.org/en-US/docs/Web/API/event.metaKey
  • a tag - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a