推文按钮打开新窗口和新标签

时间:2016-08-17 18:18:47

标签: javascript jquery twitter

我正在做FreeCodeCamp的Random Quote Machine练习。

使用this answer,我尝试设置我的推文按钮以打开一个新窗口,而不是用户可用来发布此引号的标签。

唯一的问题是它正在打开一个新标签以及一个新窗口。有什么方法可以让它打开新窗口吗?

推文链接的HTML

<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

谢谢!

1 个答案:

答案 0 :(得分: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));
});
相关问题