微信分享需要手機掃描二維碼,需要對url進行編碼。在https協議下,掃描二維碼時,瀏覽器打不開可能是安全證書導致的。
document.write("<script src='https://cdn.jsdelivr.net/npm/jquery.qrcode@1.0.3/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)
})