How to detect if user it trying to open a link in a new tab?

前端 未结 2 1171
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 05:08

I\'m writing a website in which all content is stored in the JavaScript environment, so it should be possible to navigate between \"pages\" without additional HTTP requests.

2条回答
  •  [愿得一人]
    2020-12-03 05:27

    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.

    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).

    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;
    }
    

    Fiddle: http://jsfiddle.net/6byrt0wu/

    Documentation

    • 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

提交回复
热议问题