需求描述
页面需支持微信分享功能,因两端微信JS-SDK适配成本和兼容性差异,采用不同实现方案。
PC端
由于微信的JS-SDK在PC端可能不被支持,需要AppID等配置。于是PC端调整为点击按钮时显示二维码,让用户用手机微信扫描后分享。
css样式
<style>
#qrcode-window {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background: white;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
</style>引用js文件
<script type="text/javascript" src="../qrcode.min.js"></script>body内容
<body>
<button onclick="wechatShare()">分享到微信</button>
<!-- 二维码弹窗 -->
<div id="qrcode-window">
<p>用微信扫码分享</p>
<div id="qrcode"></div>
<button onclick="document.getElementById('qrcode-window').style.display='none'">关闭</button>
</div>
<script>
function wechatShare() {
// 清空旧二维码
document.getElementById('qrcode').innerHTML = '';
// 生成当前页面链接
const url = window.location.href;
// 创建二维码(建议链接长度不要超过150字符)
new QRCode(document.getElementById('qrcode'), {
text: url,
width: 200,
height: 200
});
// 显示弹窗
document.getElementById('qrcode-window').style.display = 'block';
}
</script>
</body>移动端
由于JS-SDK需要对微信进行配置,步骤太复杂。于是将需求调整为点击按钮复制当前页面的网址。
css样式
<style>
/* 提示信息样式 */
#msgTip {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
padding: 8px 16px;
background: rgba(0,0,0,0.8);
color: white;
border-radius: 4px;
display: none;
}
</style>body内容
<body>
<button onclick="copyUrl()">复制链接</button>
<div id="msgTip">链接已复制!</div>
<script>
function copyUrl() {
//当前页面的网址
const url = window.location.href;
try {
// 优先使用旧版的,华为手机的现代Clipboard API 复制不了内容
// 兼容旧版浏览器的 fallback 方案
const textarea = document.createElement('textarea');
textarea.value = url;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
} catch(err) {
navigator.clipboard.writeText(url);
}
// 显示成功提示
const tip = document.getElementById('msgTip');
tip.textContent = '链接已复制!';
tip.style.display = 'block';
tip.style.background = isError ? '#ff4444' : '#333';
setTimeout(() => {tip.style.display = 'none';}, 2000);
}
</script>
</body>原创文章,作者:howkunet,如若转载,请注明出处:https://www.intoep.com/frontend/html/73531.html
