Twitter分享按钮动态URL分享

问题描述:

我试图制作一个自定义的Twitter按钮,当点击时会抓取当前页面的页面URL,这显然会根据它出现在哪个页面上而改变,与默认共享按钮不同。但是,我不确定如何将页面URL传递到按钮。Twitter分享按钮动态URL分享

这是我迄今jsfiddle

<style type="text/css" media="screen"> 

</style> 
<div id="social-share-container"> 
<div id="custom-tweet-button"> 
<a id="tweetShare" href="https://twitter.com/share?url="+encodeURIComponent(document.URL); target="_blank">Tweet 
    </a> 
</div> 
</div> 

这是一个有点砍死在一起,我与JS很陌生。

就以document.location看看:
location.hostname
location.pathname
http://www.w3schools.com/jsref/obj_location.asp

我建议window.location的 - 这会给你的当前页面的URL。

问题是你在HTML中使用JS内联 - 你不能像你想要的那样做。

我用一些香草js更新了你的小提琴,向你展示了一个更好的方法来做到这一点。

http://jsfiddle.net/4jF5N/1/

var link = document.getElementById('tweetShare'); 
var url = window.location; 

link.addEventListener('click',function(event){ 
    event.preventDefault(); 

    window.open("https://twitter.com/share?url="+encodeURIComponent(url)); 
    alert(url) 
},false); 
+0

它似乎并没有在之后的任何解析尽管如此,不知道这是否是JSFiddle的限制。 – RyanSoper

此经过URL和标题与Twitter共享页面简单的弹出框:

<script language="javascript"> 
    function tweetCurrentPage() 
    { window.open("https://twitter.com/share?url="+escape(window.location.href)+"&text="+document.title, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false; } 
</script> 

<a class="tweet" href="javascript:tweetCurrentPage()" target="_blank" alt="Tweet this page">Tweet this page</a> 

如果你不希望它在弹出打开框,你可以用这个来代替window.open

window.location.href="https://twitter.com/share?url="+escape(window.location.href)+"&text="+document.title; 
+0

这似乎不起作用... – Xarcell

+0

@Xarcell你可以提供更多关于它不工作的信息吗?从您的评论中无法知道是否存在实际问题,或者您是否实施了错误。这篇文章现在已经差不多三年了,所以Twitter可能会对其服务进行更改,以阻止该服务的运行或需要进行调整。我首先想到的是确保https://twitter.com/share?url=[url]&text=[text]仍然是共享的正确格式。 – wentz