微信分享需要手机扫描二维码,需要对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)
})