2016-04-02 68 views
0

我知道这是浏览器的默认行为(在新标签中打开),但是有没有什么技巧可以克服它们? 不使用其他事件处理程序 - 如<a>的onmousedown/onmouseup? 试图打开:window.open(url);如何通过点击(Chrome,Mozilla)中的新窗口来打开链接?

这是必要的,以满足需求规格。

+0

为什么要重写预期的浏览器行为? – moopet

+0

这必须在技术任务上完成。这让我疯狂了两个多星期了,是的。 –

+0

不幸的是,答案似乎是Chrome不允许JavaScript点击处理程序来打开新窗口。看[这个问题](http://stackoverflow.com/q/2572333/1016716)。 Gops AB的答案,如果你纠正错误,仍然只适用于Mozilla; ([小提琴](http://jsfiddle.net/MrLister/aeavd4L5/2/))。 –

回答

0
if (e.ctrlKey){ 
     window.open(url,'_blank') 
    } 

它将打开新选项卡中的网址。检查Click事件ctrl关键

$(".yourLink").bind('click', function(e){ 
     e.prevenDefault(); 
     if (e.ctrlKey){ 
     window.open(url,'_blank'); 
    } 
    }); 

编辑

如果你想在新窗口中打开,指定宽度和高度如下

window.open(url,'_blank', "height=255,width=255"); 
+0

@KseniyaYudina检查我的编辑 –

+0

window.open(url,_blank“,”width = 700,height = 620,“) - 在新窗口中只能在IE中打开:( –

+0

我的Chrome版本是44.0.2403.157米 –

0

实际上,它关系到CTRL键,看起来像Chrome中的一个bug,它将其作为缺省行为,即使调用了e.preventDefault()。 为了欺骗浏览器,您必须使用setTimeout函数离开侦听器堆栈。

$(".yourLink").bind('click', function(e){ 
    if (e.ctrlKey){ 
      var openWindow= function(){ 
       window.open(url,'name','width=' + screen.width + ',height=' + screen.height + ',location=yes,scrollbars=yes,status=yes;'); 
      } 
      setTimeout(openWindow, 500); 
    } 
}); 
相关问题