移动端布局参考地址

作者 新城 日期 2018-05-03
移动端布局参考地址

参考地址

代码原理

rem布局是根据html元素的font-size的大小进行按照比例缩放的 所以固定font-size、的大小 就可以改变页面适配

检测当前手机dpr从而设置htmlfont-size大小 进行适配不同手机的适配

制作页面的时候 需要按照设计图一致的大小上进行制作就可以

1rem = 100px 进行布局 所以设计图

375px == 3.75rem

使用前端ui库的时候不兼容样式 比较繁琐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'use strict';

/**
* @param {Boolean} [normal = false] - 默认开启页面压缩以使页面高清;
* @param {Number} [baseFontSize = 100] - 基础fontSize, 默认100px;
* @param {Number} [fontscale = 1] - 有的业务希望能放大一定比例的字体;
*/
const win = window;
export default win.flex = (normal, baseFontSize, fontscale) => {
const _baseFontSize = baseFontSize || 100;
const _fontscale = fontscale || 1;

const doc = win.document;
const ua = navigator.userAgent; // 获取浏览器 内核
const matches = ua.match(/Android[\S\s]+AppleWebkit\/(\d{3})/i); /// 判断Android
const UCversion = ua.match(/U3\/((\d+|\.){5,})/i);
const isUCHd = UCversion && parseInt(UCversion[1].split('.').join(''), 10) >= 80; // 判断是不是UC浏览器
const isIos = navigator.appVersion.match(/(iphone|ipad|ipod)/gi); // 判断iPhone
let dpr = win.devicePixelRatio || 1; // 获取设备的dpr
if (!isIos && !(matches && matches[1] > 534) && !isUCHd) {
// 如果非iOS, 非Android4.3以上, 非UC内核, 就不执行高清, dpr设为1;
dpr = 1;
}
const scale = normal ? 1 : 1 / dpr;

let metaEl = doc.querySelector('meta[name="viewport"]'); // 设置视口
if (!metaEl) {
metaEl = doc.createElement('meta');
metaEl.setAttribute('name', 'viewport');
doc.head.appendChild(metaEl);
}
metaEl.setAttribute('content', `width=device-width,user-scalable=no,initial-scale=${scale},maximum-scale=${scale},minimum-scale=${scale}`);
doc.documentElement.style.fontSize = normal ? '50px' : `${_baseFontSize / 2 * dpr * _fontscale}px`;
}

flex(false,100,1) // 调用函数进行适配 1rem = 100px

// 可以再厉添加 添加窗口监听事件 进行试试监听窗口的变化

注意事项

不需要手动添加适口 代码会自动添加到当前html页面头部
适配iphone5窄屏幕的时候 宽度布局使用百分比