IE 7 CTRL + click opens a new window - how to supp

2019-02-19 01:53发布

问题:

Is it possible to suppress the default IE 7 functionality when CTRL+click on link opens a new window? if so, how?

Thanks!

回答1:

There is no way to suppress a Ctrl + Click on a link with no child elements in Internet Explorer -- the onclick event doesn't fire at all for link clicks if the Ctrl key is held down. It seems that Microsoft don't want you to change this functionality out of fear that you might confuse the user.

I searched for some sort of official confirmation/explanation before posting this answer, but unfortunately this limitation is not listed in the documentation on MSDN and Google wasn't helpful. Nevertheless, it remains true, try it yourself:

<a href="#" onclick="alert('Hello');">Hello</a>

You will find that a Ctrl + click on the link will not throw the alert box. According to pinkgothic, assigning a child element to the link will work around the problem. For example:

<a href="#" onclick="alert('Hello');"><span>Hello</span></a>

This works because the click is triggered for the <span> element first, before propagating to the <a> element.



回答2:

The jQuery event.preventDefault() method or similar can override default behavior on pages that you have control over.

It is generally bad practice to alter the behaviour of a user's browser without really good reason as the browser and its behaviour is "their's".



回答3:

had the same problem as the op and solved it by giving the anchor href attribute an '#' and an additional data-href attribute with the corresponding link location. The downside you need a click handler to follow the link, also right clicking "open in new window" wont work with this approach.

eg: In AnchorTag, Use href and data-ref as:
<a id="logout" href="#" data-href="${yourPath}"> 

And in javascript, use    
$("#logout").click(function(e) {
    if(e.ctrlKey) 
e.preventDefault();
window.location = $(e.target).attr("data-href");
});


回答4:

wrap your link text inside an span. like this:

<a href="test.html"><span>click here!</span></a>


回答5:

Add script to the anchor and return false

<a href='some.htm' onclick='return false;'></a>

And it is valid to use anchors in a treeview because it makes the treeview more accessible.



回答6:

Using jquery you can handle the ctrl+click functionality for yourself and return false, for example

$("a").click(function(event){
if(event.metaKey || event.ctrlKey){
 //handle over here 

return false;
}

});

this works across all browsers including mac