2014-02-25 105 views
1

我希望當用戶單擊鏈接時,默認情況下,網站中的所有鏈接都會打開到新的背景選項卡。我已經檢查了所有,但他們都沒有提供適用於所有瀏覽器的解決方案。我已經提到了以下兩個鏈接給我寫代碼:使用javascript/jquery打開新背景選項卡中的鏈接

Working example in chrome

Suggested modifications for ie

我有以下代碼:

<html> 
<head> 
<style type="text/css"> 
.link{ color: #0055ff; cursor: pointer; text-decoration: underline; } 
</style> 


<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
$(".link").on('click', function(event){ 
var $this = $(this); 
    var a = document.createElement("a"); 

    a.href = $this.href; 


    if(document.createEvent) { 
     var evObj = document.createEvent('MouseEvents'); 
     evObj.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, 
          true, false, false, true, 1, a); 
     a.dispatchEvent(evObj); 

    } else if(document.createEventObject) { 
     var evObj = document.createEventObject(); 
     evObj.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, 
          true, false, false, true, 1, a); 
     a.fireEvent('onclick', evObj); 
    } 
}); 
}); 
</script> 
</head> 
<body> 
<span class="link" data-href="http://www.google.com">Go to Google</span> 
</body> 
</html> 
+0

可能重複[javascript window.location在新標籤](http://stackoverflow.com/questions/7554108/javascript-window-location-in-new-tab) – Andy

+1

谷歌爲window.open –

+0

在鏈接上以編程方式觸發鼠標事件將觸發瀏覽器的彈出窗口阻止程序。如果鏈接被點擊,只需做一個簡單的'window.open'。 – Christoph

回答

2

的jQuery(將通過彈出窗口阻止程序停止)

<html> 
<head> 
<style type="text/css"> 
.link{ color: #0055ff; cursor: pointer; text-decoration: underline; } 
</style> 


<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
$(".link").on('click', function(event){ 
var $this = $(this); 

    window.open($this.href, '_blank'); 

}); 
}); 
</script> 
</head> 
<body> 
<span class="link" data-href="http://www.google.com">Go to Google</span> 
</body> 
</html> 

Javascript(will not be)通過彈出窗口阻止程序停止)

<html> 
<head> 
<style type="text/css"> 
.link{ color: #0055ff; cursor: pointer; text-decoration: underline; } 
</style> 
</head> 
<body> 
<span class="link" onclick="window.open('http://www.google.com', '_blank')">Go to Google</span> 
</body> 
</html> 

註釋雖然,基於問題的話題:

人們做出選擇的瀏覽器應該如何行事,它並不意味着我們開發人員重寫...一個更好的方法是向他們提供一種方式,通過詢問他們是否希望在新標籤頁/窗口中打開或者不在首位......其次,告訴他們爲什麼他們應該按照你的喜好去做,在您的網站上這樣做的好處。這可能會讓你想要的地方

+0

你的代碼將打開新鏈接作爲前景選項卡,而不是作爲背景選項卡,即,我希望用戶保持當前選項卡上的鏈接被點擊的位置,並且新鏈接必須在後臺加載。 – Bharat

+1

這是由用戶設置的瀏覽器設置。你不能用javascript來決定。 – LGSon

相關問題