Skip to content

移动端经验总结

记录移动端(H5、小程序、App)开发中常见的问题和解决方案

H5 移动端适配

视口配置

html
<meta
  name="viewport"
  content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>

rem 适配方案

使用 postcss-pxtorem + amfe-flexible 进行移动端适配:

bash
npm install postcss-pxtorem amfe-flexible -D
js
// postcss.config.js
module.exports = {
  plugins: {
    "postcss-pxtorem": {
      rootValue: 37.5, // Vant 组件库基于 375px 设计稿
      propList: ["*"],
      selectorBlackList: [".norem"], // 不需要转换的类名
    },
  },
};

vw 适配方案(推荐)

bash
npm install postcss-px-to-viewport-8-plugin -D
js
// postcss.config.js
module.exports = {
  plugins: {
    "postcss-px-to-viewport-8-plugin": {
      viewportWidth: 375,
      unitPrecision: 5,
      viewportUnit: "vw",
      selectorBlackList: [".novw"],
      minPixelValue: 1,
    },
  },
};

移动端常见问题

1px 边框问题

高 DPR 屏幕下 1px 显示较粗,解决方案:

css
.border-bottom {
  position: relative;
}
.border-bottom::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-color: #e5e5e5;
  transform: scaleY(0.5);
}

安全区域适配(iPhone 刘海屏)

css
/* 底部安全区域 */
.footer {
  padding-bottom: constant(safe-area-inset-bottom); /* iOS 11.0-11.2 */
  padding-bottom: env(safe-area-inset-bottom); /* iOS 11.2+ */
}

点击延迟(300ms 问题)

现代浏览器已基本修复,如仍需处理可使用 fastclick 或设置:

css
html {
  touch-action: manipulation;
}

软键盘弹出导致页面变形

js
// 监听键盘弹出/收起
const originalHeight = document.documentElement.clientHeight;
window.addEventListener("resize", () => {
  const currentHeight = document.documentElement.clientHeight;
  if (currentHeight < originalHeight) {
    // 键盘弹出
  } else {
    // 键盘收起
  }
});

图片模糊问题

在高 DPR 设备上使用 2x/3x 图片:

html
<img
  srcset="logo@1x.png 1x, logo@2x.png 2x, logo@3x.png 3x"
  src="logo@2x.png"
  alt="logo"
/>

小程序端经验

包体积优化

  1. 使用分包加载,主包控制在 2MB 以内
  2. 图片资源使用网络地址,不放在本地
  3. 清理未使用的代码和依赖

小程序登录流程

用户点击登录 → wx.login() 获取 code → 发送 code 到后端 → 后端换取 openid/session_key → 返回自定义 token

授权与隐私

  1. 用户信息授权需使用按钮触发(<button open-type="getUserInfo">
  2. 位置、相册等敏感权限需要提前在 app.json 中声明
  3. 注意隐私协议弹窗的合规要求

App 端经验

WebView 通信

js
// H5 向 App 发送消息
window.webkit.messageHandlers.nativeMethod.postMessage(data); // iOS
window.android.nativeMethod(data); // Android

// App 向 H5 发送消息(通过 URL scheme 或 JS 注入)

调试技巧

  1. Chrome 远程调试chrome://inspect 调试 Android WebView
  2. Safari 调试:开发菜单中调试 iOS WebView
  3. vConsole / Eruda:页面内嵌调试面板,适用于真机调试