推特分享按钮动态网址分享

Twitter Share button dynamic URL share

本文关键字:分享 动态 按钮      更新时间:2023-09-26

我正在尝试制作一个自定义Twitter按钮,该按钮在单击时将抓取当前页面的页面URL,这显然会根据它出现在哪个页面上而变化,这与默认共享按钮不同。但是,我不确定如何将页面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 很不熟悉。

这会将 url 和标题传递到带有 Twitter 共享页面的简单弹出框中:

<script language="javascript">
    function tweetCurrentPage()
    { window.open("https://twitter.com/share?url="+ encodeURIComponent(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="+ encodeURIComponent(window.location.href)+"&text="+document.title;

更新: escape()函数已弃用,替换为encodeURIComponent()

我建议window.location - 这将为您提供当前页面网址。

问题是你在 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);

看看 document.location:
位置.主机名
位置.路径名
http://www.w3schools.com/jsref/obj_location.asp