skip to content

📱移动 Web 开发

  • 运行在手机端的 Web 页面(H5 页面)
  • 跨平台
  • 基于 Webview
  • 告别 IE 拥抱 Webkit
  • 更好的适配性能要求

常见移动 web 适配方法

PC

  • 960px / 1000px 居中
  • 盒子模型,定高,定宽
  • display:inline-block

移动 web

  • 定高,宽度百分比
  • Flex 布局
  • Media Query(媒体查询)

Media Query(媒体查询)

@media 媒体类型 and (媒体特性) {
  /*css样式*/
}

举个例子

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      .inner {
        text-align: center;
        color: white;
        line-height: 100px;
        font-size: 24px;
      }

      .box .inner:nth-child(2n) {
        background: palegreen;
      }

      .box .inner:nth-child(2n + 1) {
        background: palevioletred;
      }

      @media screen and (max-width: 320px) {
        .inner {
          width: 100%;
        }
      }

      @media screen and (min-width: 321px) {
        .inner {
          width: 25%;
          float: left;
        }
      }
    </style>
  </head>

  <body>
    <div class="box">
      <div class="inner">1</div>
      <div class="inner">2</div>
      <div class="inner">3</div>
      <div class="inner">4</div>
    </div>
  </body>
</html>

rem 布局

rem:font size of the root element

  • 字体单位:值根据 html 根元素大小而定,同样可以作为宽度高度等单位
  • 适配原理:将 px 替换成 rem,动态修改 htmlfont-size 适配
  • 兼容性:IOS 6 以上和 Android 2.1 以上,基本覆盖所有流行的手机系统

使用流程

使用设备:iPhone 6/7/8

切图:750px x 1334px 两倍图

  1. 使用 JS 动态修改 htmlfont-size

    function setFontSize() {
      //得到手机屏幕的宽度
      let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
      //得到html的Dom元素
      let htmlDom = document.getElementsByTagName('html')[0]
      //设置根元素字体大小
      htmlDom.style.fontSize = htmlWidth / 10 + 'px'
    }
    setFontSize()
    window.addEventListener('resize', function (e) {
      setFontSize()
    })
    
  2. 使用 scss 编写 px 转换成 rem 的函数

    @function px2rem($px) {
      $rem: 37.5px;
      @return ($px/$rem) + rem;
    }
    
  3. 愉快的编写样式代码喽

    .box {
      width: px2rem(100px);
      height: px2rem(100px);
      font-size: px2rem(24px);
    }
    

参考:

移动 Web 开发适配秘籍 Rem

关于移动端适配,你必须要知道的