移动端使用 rem 适配,iOS 真机上出现宽度失效的问题

  • 这段代码是一个用于移动端响应式布局的 REM 自适应方案,其核心原理是通过动态调整根元素(html)的字体大小(font-size),使得页面元素能够根据屏幕宽度等比缩放。
  • 假设设计稿宽度为 1080px,定义 1rem = 100px。
    • 设计稿中 100px 的元素 → 代码写为 1rem。
    • 根字体大小 = (当前视口宽度 / 设计稿宽度) * 100px
(function (doc, win, designWidth) {
  var html = doc.documentElement; // 获取 HTML 根元素
  function refreshRem() {
    var clientWidth = html.clientWidth; // 获取视口宽度(设备独立像素,如 375px)
    
    // 判断视口宽度是否超过设计稿宽度(1080px)
    if (clientWidth >= designWidth) {
      html.style.fontSize = '100px'; // 超过则固定根字体为 100px
    } else {
      // 未超过则按比例计算根字体大小
      html.style.fontSize = 100 * (clientWidth / designWidth) + 'px';
    }
  };
  
  // DOM 加载完成后初始化 REM
  doc.addEventListener('DOMContentLoaded', refreshRem);
})(document, window, 1080); // 传入参数:document, window, 设计稿宽度 1080px
  • 在移动端使用 rem 适配时,iOS 真机上出现宽度失效的问题,通常是由于 iOS Safari 的特殊渲染机制 或 REM 计算时机问题 导致的。以下是针对你提供的代码的优化方案和解决方案:

  • CSS 重置IOS样式

  /* 重置 iOS 默认样式 */
  html {
    -webkit-text-size-adjust: 100%; /* 禁止字体缩放 */
    -webkit-tap-highlight-color: transparent; /* 禁用点击高亮 */
  }

  body {
    font-size: 0.16rem; /* 设置基准字体大小 */
  }

  /* 清除元素默认样式 */
  button, input, select, textarea {
    -webkit-appearance: none;
    appearance: none;
    min-width: 0; /* 关键:覆盖 iOS 的默认 min-width */
    box-sizing: border-box;
    border-radius: 0;
  }

  /* 确保所有元素使用 rem */
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  /* 修复 button 在 iOS 上的问题 */
  button {
    min-width: 0 !important;
    width: 100%; /* 或固定 rem 值如 1.6rem */
    overflow: visible; /* 解决内容被裁剪 */
  }

  /* 修复 input 在 iOS 上的问题 */
  input {
    border: 1px solid #ccc; /* 确保边框可见 */
    height: 0.88rem; /* 建议使用固定 rem 高度 */
  }
posted @ 2025-03-31 17:23  HuangBingQuan  阅读(85)  评论(0)    收藏  举报