在移动端开发过程中,我们需要适配各种不同机型的屏幕,如何能够写一套代码适,做到屏幕的完美适配呢。针对设计稿为750*1334,自己常用的适配方案如下
1 2 3 4 5 6 7 8 9 10 11 12 13
| (function(doc, win){ var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function(){ var clientWidth = docEl.clientWidth; if(!clientWidth) return; docEl.style.fontSize = 100 * (clientWidth / 375) + 'px'; };
if(!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window);
|
对应样式
1 2 3 4
| .wrapper{ padding: .2rem .3rem; }
|
将js作为单独文件或者嵌入到页面的头部,防止因为js文件加载慢而引起页面错乱!
1 2 3 4 5 6 7 8 9 10 11
| var dpr, rem, scale; var docEl = document.documentElement; var fontEl = document.createElement('style'); var metaEl = document.querySelector('meta[name="viewport"]'); dpr = window.devicePixelRatio || 1; scale = 1 / dpr; rem = docEl.clientWidth * dpr / 10; metaEl.setAttribute('content', 'width=' + dpr * docEl.clientWidth + ',initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale + ',user-scalable=no'); docEl.setAttribute('data-dpr', dpr); docEl.firstElementChild.appendChild(fontEl); fontEl.innerHTML = 'html{font-size:' + rem + 'px!important;}';
|
scss
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
| $baseFontSize: 75px !default; $dpr : 1 !default;
@function px2rem($px) { @if $dpr == 2 { @return ($px / $baseFontSize) * 1rem; } @else if $dpr == 2.5 { @return ($px * 2.5 /$baseFontSize * 2) * 1rem; } @else if $dpr == 2.75 { @return ($px * 2.75 / $baseFontSize * 2) * 1rem; } @else if $dpr == 3 { @return ($px * 3 / $baseFontSize * 2) * 1rem; } @else { @return ($px / $baseFontSize * 2) * 1rem; }
} @function px2px($px) { @if $dpr == 2 { @return ($px/2) * 1; } @else if $dpr == 2.5 { @return ($px * 2.5 / 2) * 1; } @else if $dpr == 2.75 { @return ($px * 2.75 / 2) * 1; } @else if $dpr == 3 { @return ($px * 3 / 2) * 1; } @else { @return ($px * 2) * 1; } }
height: px2rem(50px); font-size: px2rem(16px);
|
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| @media (min-width: 320px){ html, body{ font-size: 42.7px; } } @media (min-width: 340px){ html, body{ font-size: 45.3px; } } @media (min-width: 360px){ html, body{ font-size: 48px; } } @media (min-width: 375px){ html, body{ font-size: 50px; } } @media (min-width: 400px){ html, body{ font-size: 53.3px; } } @media (min-width: 414px){ html, body{ font-size: 55.2px; } } @media (min-width: 768px){ html, body{ font-size: 102.4px; } } @media (min-width: 992px){ html, body{ font-size: 132.7px; } } @media (min-width: 1200px){ html, body{ font-size: 160px; } } body{ font-size: .24rem; }
.wrapper{ padding: .1rem .15rem; }
|
tips
当然了,你本来是在移动端适配,如果有人在PC端打开(尤其是微信内的推广活动),可以设置一个html的最大宽度和最小高度。比如:
1 2 3 4
| html,body{ max-width: 600px; min-height: 320px; }
|