david2tdw / blog

学习记录
1 stars 1 forks source link

[mobile] 移动页面适配 #154

Open david2tdw opened 4 years ago

david2tdw commented 4 years ago

image

david2tdw commented 4 years ago

设备像素比 = 物理像素(固定值) / 设备独立像素(CSS像素值)

计稿尺寸为750px.

以iphone6为例: 2 = 750pt / 375pt

将设计稿分为100份,rem缩放比例为:

375 (物理像素)/ 750(CSS像素) = ? / 100 (CSS尺寸)

var width = document.documentElement.clientWidth;   // 屏幕的布局视口宽度:375
var rem = width * 100 / 750 = 375 *  100 / 750 = 375 / 7.5;   // 750px设计稿将布局视口分为7.5份

1rem 等于设计稿上的100px。故px转换rem时:

?rem = ??px / 100;

移动端页面适配———多方案解析

david2tdw commented 4 years ago

在750px设计稿上解析:

75px 对应 0.75rem, 距离占设计稿的10%;

在ipone6上:
width = document.documentElement.clientWidth = 375px;
rem = 375px / 7.5 = 50px;
0.75 * rem = 37.5px;   (37.5/375=10%;占屏幕10%)

在ipone5上:
width = document.documentElement.clientWidth = 320px;
rem = 320px / 7.5 = 42.667px;
0.75 * rem = 32px; (32/320=10%;占屏幕10%)
david2tdw commented 4 years ago

rem中根元素font-size设定:

width = document.documentElement.clientWidth
if (/mobile/i.test(navigator.userAgent)) {
    document.documentElement.style.fontSize = (width / 7.5 ) + 'px'
  } else {
    document.documentElement.style.fontSize = 16 + 'px'
  }
david2tdw commented 4 years ago

适配方案:

  1. 媒体查询。
  2. vw, vh方式。
  3. rem 方式
  4. flex布局方式
david2tdw commented 4 years ago

API: iPhone6为例:

布局视口: 布局视口是看不见的,浏览器厂商设置的一个固定值

document.documentElement.clientHeight;
667
document.documentElement.clientWidth;
375

视觉视口: 浏览器可视区域的大小,即用户看到的网页的区域。(其宽度继承的布局视口宽度)

window.innerHeight;
667
window.innerWidth;
375
david2tdw commented 4 years ago

rem适配: 需要适配的元素使用rem,不需要适配的元素使用px。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
  <title>移动适配</title>
  <style>
    .content {
      font-size: .6rem;
    }
  </style>
  <script>
    const WIDTH = 750 //设计稿尺寸
    const setView = () => {
      console.log('setView')
      document.documentElement.style.fontSize = (100 * screen.width / WIDTH) + 'px'
    }
    window.onorientationchange = setView
    window.onresize = setView
    setView()
  </script>
</head>
<body>
  <div class="content">
    字体应该使用px,不应该使用rem。
  </div>
</body>
</html>

移动端适配的几种方案