查看: 305|回复: 0

[js/typscript] 微信小程序开发web页面进行UA适配的方法

[复制链接]

748

主题

39

回帖

3907

积分

管理员

总舵主

积分
3907
QQ
发表于 2025-12-8 16:38:14 | 显示全部楼层 |阅读模式
创建获取UA的代码函数:

  1. function getos() {
  2.     const ua = window.navigator.userAgent.toLowerCase();

  3.     const isWindows = ua.indexOf("windows") !== -1;

  4.     const isHarmony = ua.indexOf("openharmony") !== -1;
  5.     const isHarmonyPC = isHarmony && ua.indexOf("pc;") !== -1;

  6.     const isRealIpadUA = ua.indexOf("ipad") !== -1;
  7.     const isMaskedIpad = ua.indexOf("macintosh") !== -1 && navigator.maxTouchPoints > 1;  // 伪装 iPad: UA 包含 "macintosh" 但支持触控 (系统认为是桌面模式)
  8.     const isMac = ua.indexOf("macintosh") !== -1;

  9.     return {
  10.         isWechat: ua.indexOf("micromessenger") !== -1,  // 是否为微信客户端浏览器

  11.         isAndroid: ua.indexOf("android")!==-1 && !isHarmony,  // Android 手机,排除 Harmony
  12.         isIphone: ua.indexOf("iphone")!==-1|| ua.indexOf("ipod")!==-1,  // Iphone 手机等移动设备
  13.         isHarmony: isHarmony && !isHarmonyPC,  // Harmony 手机 (排除 Harmony PC)
  14.         isIpad: isRealIpadUA || isMaskedIpad,  // iPad 或 伪装 Mac 的 iPad

  15.         isWindows,      // Windows 电脑
  16.         isHarmonyPC,    // 鸿蒙 PC
  17.         isMac,          // Mac 电脑 (也包含桌面模式的 iPad)

  18.         isPC: isMac || isWindows || isHarmonyPC  // 广义 PC:用于判断是否展示宽屏/桌面版 UI
  19.     };
  20. }
复制代码
使用时:
  1. const os  = getos()

  2. if (os.isWechat) {}       // 微信客户端浏览器处理逻辑

  3. // 移动端处理逻辑

  4. if (os.isAndroid) {}      // Android 手机、平板处理逻辑
  5. if (os.isHarmony) {}      // HarmonyOS 手机、平板处理逻辑
  6. if (os.isIphone) {}       // Iphone 手机处理逻辑
  7. if (os.isIpad) {}         // iPad 手机处理逻辑

  8. // PC处理逻辑

  9. if (os.isHarmonyPC) {}    // HarmonyOS PC处理逻辑
  10. else if (os.isMac) {}     // Mac处理
  11. else if (os.isWindows) {} // windows处理

  12. if (os.isPC) {}           // 桌面版浏览器处理逻辑
复制代码


道不同,不相为谋!理想要有,万一实现了呢?
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注公众号

相关侵权、举报、投诉及建议等,请发 E-mail:2513533699@qq.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.|鲁ICP备19000917号|鲁公网安备37078302000320号

在本版发帖
关注公众号
QQ客服返回顶部