PC/移动端微信分享适配方案

微信JS-SDK配置繁琐,PC端还不支持?本文分享一种无需AppID和签名的纯前端适配方案:PC端优雅展示二维码,移动端一键复制链接,轻松解决跨端分享难题。

需求描述

页面需支持微信分享功能,因两端微信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

(0)
使用 HTML+CSS 打造高颜值信用卡支付表单
上一篇 2026-01-15 09:56
CSS适配iOS全面屏底部横条
下一篇 2023-12-28 18:12

发表回复

登录后才能评论
扫码了解
扫码了解
反馈建议
分享本页
返回顶部