移动端自适应解决方案
基础概念
CSS 像素(CSS Pixel):
又称为虚拟像素、设备独立像素或逻辑像素,也可以理解为直觉像素。CSS 像素是 Web 编程的概念,指的是 CSS 样式代码中使用的逻辑像素。比如 iPhone 6 的 CSS 像素数为 375 x 667px。
设备像素(Device Pixels):
又称为物理像素。指设备能控制显示的最小物理单位,意指显示器上一个个的点。从屏幕在工厂生产出的那天起,它上面设备像素点就固定不变了。比如 iPhone 6 的分辨率为 750 x 1334px
设备像素比(DevicePixelRatio):DPR = 设备像素 / CSS 像素
这里的 CSS 像素其实是理想视口
例如,iPhone 6 物理像素为 750 x 1334,理想视口 375 x 667 ,DPR = 2
pc端 css像素可以与设备像素一一对应,但是移动端,设备像素是不变端但是,css像素变小了,可以能出现一个css像素对应2、3个设备像素,css像素好比一个视口。
方案一: 动态更改根元素font-size,使用rem
原理: 以 750px 为基准做设计图,物理像素375px,初始设置font-size:100,根据不同设备分辨率大小相对应更改font-size. 样式中使用rem
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
| new function () { var _self = this; _self.width = 750; _self.fontSize = 100; var agent = navigator.userAgent var isMobile = !!agent.match(/AppleWebKit.*Mobile.*/) if (isMobile) { _self.widthProportion = function () { var p = (document.body && document.body.clientWidth || document.getElementsByTagName("html")[0].offsetWidth) / _self.width; return p; }; _self.changePage = function () { document.getElementsByTagName("html")[0].setAttribute("style", "font-size:" + _self.widthProportion() * _self.fontSize + "px !important"); }; _self.changePage(); if( window.addEventListener ){ window.addEventListener('resize', _self.changePage(), false) }else if (window.attachEvent){ window.attachEvent('resize', _self.changePage()) } } else { document.getElementsByTagName("html")[0].setAttribute("style", "font-size: 50px !important"); } };
|
方案二: 京东移动端适配-原理同样是改变font-size,不过是使用媒体查询,vw+rem搭配使用
同样以 设备像素750px为基准,但是css像素375px(100vw), 设置font-size:20vw 相当于font-size:75px
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
| :root { --vw_design:750; --vw_fontsize:75; }
html { display: block; color: -internal-root-color; font-size: 20vw; } @media screen and (max-width: 320px) { html { font-size: 64px } }
@media screen and (min-width: 540px) { html { font-size: 108px } }
body { max-width: 960px; min-width: 320px; }
|
1 2 3 4 5 6
| @vw_fontsize: 75;
.px2rem(@name, @px){ @{name}: @px / @vw_fontsize * 1rem; }
|
手机淘宝——flexible.js 移动端自适应方案
原理差不多,设置font-size,dpr,使用rem,可以自行查看源码
1 2 3
| <script src="http://g.tbcdn.cn/mtb/lib-flexible/0.3.2/??flexible_css.js,flexible.js" ></script>
|