繁体   English   中英

Twitter分享按钮动态URL共享

[英]Twitter Share button dynamic URL share

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

这就是我到目前为止所说的

<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和title传递给一个带有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:
location.hostname
location.pathname
http://www.w3schools.com/jsref/obj_location.asp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM