1. 程式人生 > 其它 >JS PC網頁端實現QQ、微信、新浪微博分享功能

JS PC網頁端實現QQ、微信、新浪微博分享功能

微信分享需要手機掃描二維碼,需要對url進行編碼。在https協議下,掃描二維碼時,瀏覽器打不開可能時安全證書導致的。

   document.write("<script language=javascript src='https://cdn.bootcdn.net/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js'></script>");
  
    var ShareTip =  {
        shareToWx: function () {  // 分享到微信的二維碼
            $("#qrcode").qrcode({
                text: path,            
// 設定二維碼內容 render: "table", // 設定渲染方式 width: 256, // 設定寬度,預設生成的二維碼大小是 256×256 height: 256, // 設定高度 typeNumber: -1, // 計算模式 background: "#ffffff", // 背景顏色 foreground: "#000000" // 前景顏色 }); }, shareToQq:
function (content, url, picurl) { // 分享到騰訊QQ var shareqqstring = 'https://connect.qq.com/widget/shareqq/index.html?url=' + encodeURIComponent(url) + '&title=' + content + '&desc='+content+'&pics=' + picurl; window.open(shareqqstring); }, shareToQqzone:
function (title, url, picurl) { // 分享到QQ空間 var shareqqzonestring = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + encodeURIComponent(url) + '&title=' + title + '&desc=' + title + '&pics=' + picurl; window.open(shareqqzonestring); }, shareToSina: function (title, url, picurl) { // 分享到新浪微博 var sharesinastring = 'http://v.t.sina.com.cn/share/share.php?url=' + encodeURIComponent(url) +'&title=' + title + '&content=utf-8&sourceUrl=' + url + '&pic=' + picurl+'&searchPic=true#_loginLayer_1639641926022'; window.open(sharesinastring); }, getImages: function (str,cnt = false) {// 獲取文章圖片 var images = [] var imgReg = /<img.*?(?:>|\/>)/gi; // 匹配圖片(g表示匹配所有結果i表示區分大小寫) var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; // 匹配src屬性 var arr = str.match(imgReg); // console.log('所有已成功匹配圖片的陣列:' + arr); if(!cnt){ return document.domain + arr[0].match(srcReg)[1] } for (var i = 0; i < arr.length; i++) { var src = arr[i].match(srcReg); // 獲取圖片地址 if (src[1]) { // console.log('已匹配的圖片地址' + (i + 1) + ':' + src[1]); images.push(document.domain + src[1]) } } return images } }

使用方法

    var path = window.location.href
    var title = $(".title").html();
    var picurl = ShareTip.getImages('<?=$row["content"]?>')

    $(".sharetowx").click(function(params) {
        ShareTip.shareToWx($("#qrcode"))
    })
    $(".sharetosina").click(function(params) {
        ShareTip.shareToSina(title, path, picurl)
    })
    $(".sharetoqq").click(function(params) {
        ShareTip.shareToQq(title, path, picurl)
    })
    $(".sharetoqqzone").click(function(params) {
        ShareTip.shareToQqzone(title, path, picurl)
    })