2016-04-02 66 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); 
    } 
}); 
相關問題