2016-08-17 91 views
1

我在做FreeCodeCamp的隨機引用機練習。鳴叫按鈕打開新窗口和新標籤

使用this answer,我嘗試設置我的推文按鈕來打開一個新窗口,而不是用戶可以使用此引號引用的選項卡。

唯一的問題是它打開一個新標籤以及一個新窗口。有什麼辦法可以打開新窗口嗎?

爲HTML鏈接分享Tweet

<a class="twitter-share-button" href="https://twitter.com/intent/tweet" target="_newwin"> 
Tweet</a> 

相關的JavaScript

jQuery('a[target^="_newwin"]').click(function() { 
    var width = 500; 
    var height = 300; 
    window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height)/2) + ', left=' + ((window.innerWidth - width)/2)); 
}); 

Pen of my Project

謝謝!

+0

在猜測新窗口(或標籤)是因爲錨的默認行爲打開,嘗試http://stackoverflow.com/questions/3786898/jquery-anchor-preventdefault – yuriy636

+1

一個簡單的解決方法是在你的錨上添加'onclick =「return false;」'。 –

回答

3

您正在同時獲得自定義行爲(打開一個新窗口)和鏈接的標準行爲(在大多數瀏覽器中,現在打開一個新標籤)。爲了防止後者,你需要使用'preventDefault'方法:

jQuery('a[target^="_newwin"]').click(function(e) { 
    e.preventDefault(); 
    var width = 500; 
    var height = 300; 
    window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height)/2) + ', left=' + ((window.innerWidth - width)/2)); 
}); 
+0

這解決了我的問題,並讓我更瞭解preventDefault()的用途,謝謝Martin! –