移动端网页布局适配rem方案小结

4次阅读

共计 5564 个字符,预计需要花费 14 分钟才能阅读完成。

前言
根据 W3C 规范中对 1rem 的定义:
1rem 与等于根元素 font-size 的计算值。当明确规定根元素的 font-size 时,rem 单位以该属性的初始值作参照。这就意味着 1rem 等于 html 元素的字体大小(大部分浏览器根元素的字体大小为 16px)

兼容性
ios:6.1 系统以上都支持
android:2.1 系统以上都支持
大部分主流浏览器都支持,可以安心的往下看了。

rem:(font size of the root element)
意思就是根据网页的根元素来设置字体大小,和 em(font size of the element)的区别是,em 是根据其父元素的字体大小来设置,而 rem 是根据网页的跟元素(html)来设置字体大小的,举一个简单的例子,
现在大部分浏览器 IE9+,Firefox、Chrome、Safari、Opera,如果我们不修改相关的字体配置,都是默认显示 font-size 是 16px,即
html {
font-size:16px;
}

那么如果我们想给一个 P 标签设置 12px 的字体大小,那么用 rem 来写就是
p {
font-size: 0.75rem; //12÷16=0.75(rem)
}

使用 rem 这个字体单位进行适配,就是利用它作为一个全局字体固定参照单位的特性。如果改变 html 元素的字体大小,rem 的值也就跟着改变,对应的其他使用 rem 的布局尺寸,也会跟着改变,从而达到适配的目的,保证比例一致。所以 rem 不仅可以适用于字体,同样可以用于 width height margin 这些样式的单位。
rem 适配具体实现方案:
设计稿尺寸宽度为 750px,如果设计稿是 640px,下边 js 会自动计算 rem 的值(比如 rem:75px -> rem: 64px),具体的尺寸 rem 不用调整(例如 padding: 1.5rem,不用调整,这是一个比例大小),对应的元素大小 px 值会根据新的 rem(比如 rem: 64px, padding 等于 1.5 * 64)改变,从而按照比例适配。
index.html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>rem 适配 </title>
<script>;(function(win, lib) {
var doc = win.document;
var docEl = doc.documentElement;
var metaEl = doc.querySelector(‘meta[name=”viewport”]’);
var flexibleEl = doc.querySelector(‘meta[name=”flexible”]’);
var dpr = 0;
var scale = 0;
var tid;
var flexible = lib.flexible || (lib.flexible = {});

if (metaEl) {
console.warn(‘ 将根据已有的 meta 标签来设置缩放比例 ’);
var match = metaEl.getAttribute(‘content’).match(/initial\-scale=([\d\.]+)/);
if (match) {
scale = parseFloat(match[1]);
dpr = parseInt(1 / scale);
}
} else if (flexibleEl) {
var content = flexibleEl.getAttribute(‘content’);
if (content) {
var initialDpr = content.match(/initial\-dpr=([\d\.]+)/);
var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/);
if (initialDpr) {
dpr = parseFloat(initialDpr[1]);
scale = parseFloat((1 / dpr).toFixed(2));
}
if (maximumDpr) {
dpr = parseFloat(maximumDpr[1]);
scale = parseFloat((1 / dpr).toFixed(2));
}
}
}

if (!dpr && !scale) {
var isAndroid = win.navigator.appVersion.match(/android/gi);
var isIPhone = win.navigator.appVersion.match(/iphone/gi);
var devicePixelRatio = win.devicePixelRatio;
if (isIPhone) {
// iOS 下,对于 2 和 3 的屏,用 2 倍的方案,其余的用 1 倍方案
if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
dpr = 3;
} else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){
dpr = 2;
} else {
dpr = 1;
}
} else {
// 其他设备下,仍旧使用 1 倍的方案
dpr = 1;
}
scale = 1 / dpr;
}

docEl.setAttribute(‘data-dpr’, dpr);
if (!metaEl) {
metaEl = doc.createElement(‘meta’);
metaEl.setAttribute(‘name’, ‘viewport’);
metaEl.setAttribute(‘content’, ‘initial-scale=’ + scale + ‘, maximum-scale=’ + scale + ‘, minimum-scale=’ + scale + ‘, user-scalable=no’);
if (docEl.firstElementChild) {
docEl.firstElementChild.appendChild(metaEl);
} else {
var wrap = doc.createElement(‘div’);
wrap.appendChild(metaEl);
doc.write(wrap.innerHTML);
}
}

function refreshRem(){
var width = docEl.getBoundingClientRect().width;
if (width / dpr > 540) {
width = 540 * dpr;
}
var rem = width / 10;
docEl.style.fontSize = rem + ‘px’;
flexible.rem = win.rem = rem;
}

win.addEventListener(‘resize’, function() {
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}, false);
win.addEventListener(‘pageshow’, function(e) {
if (e.persisted) {
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}
}, false);

if (doc.readyState === ‘complete’) {
doc.body.style.fontSize = 12 * dpr + ‘px’;
} else {
doc.addEventListener(‘DOMContentLoaded’, function(e) {
doc.body.style.fontSize = 12 * dpr + ‘px’;
}, false);
}

refreshRem();

flexible.dpr = win.dpr = dpr;
flexible.refreshRem = refreshRem;
flexible.rem2px = function(d) {
var val = parseFloat(d) * this.rem;
if (typeof d === ‘string’ && d.match(/rem$/)) {
val += ‘px’;
}
return val;
}
flexible.px2rem = function(d) {
var val = parseFloat(d) / this.rem;
if (typeof d === ‘string’ && d.match(/px$/)) {
val += ‘rem’;
}
return val;
}

})(window, window[‘lib’] || (window[‘lib’] = {}));</script>
</head>
<body>
<noscript>
<strong>We’re sorry but rem 适配 doesn’t work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id=”app”></div>
<!– built files will be auto injected –>
</body>
</html>

helper.scss
$remBase: 75;
$primaryColor: #ffd633;

@function px2rem($px) {
@return ($px / $remBase) * 1rem;
}

%textOverflow {
width: 100%;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}

// @include borderLineTop(‘top’, color)
@mixin borderLine($mode: ‘top’, $color: #e5e5e5) {
position: relative;
@if $mode == ‘top’ {
&::before {
// 实现 1 物理像素的下边框线
content: ”;
position: absolute;
z-index: 1;
pointer-events: none;
background-color: $color;
height: 1px;
left: 0;
right: 0;
top: 0;
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
-webkit-transform: scaleY(0.5);
-webkit-transform-origin: 50% 0%;
}
}
}
@if $mode == ‘bottom’ {
&::after {
// 实现 1 物理像素的下边框线
content: ”;
position: absolute;
z-index: 1;
pointer-events: none;
background-color: $color;
height: 1px;
left: 0;
right: 0;
bottom: 0;
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
-webkit-transform: scaleY(0.5);
-webkit-transform-origin: 50% 0%;
}
}
}
}

@mixin borderRadius($radius) {
border-top-left-radius: px2rem($radius);
border-top-right-radius: px2rem($radius);
border-bottom-left-radius: px2rem($radius);
border-bottom-right-radius: px2rem($radius);
}

// @include banner(100)
@mixin banner($height) {
position: relative;
padding-top: percentage($height/750); // 使用 padding-top
height: 0;
overflow: hidden;
img {
width: 100%;
height: auto;
position: absolute;
left: 0;
top: 0;
}
}

$spaceamounts: (5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 100);

$sides: (top, bottom, left, right);
@each $space in $spaceamounts {
@each $side in $sides {
.m-#{str-slice($side, 0, 1)}-#{$space} {
margin-#{$side}: #{px2rem($space)} !important;
}
.p-#{str-slice($side, 0, 1)}-#{$space} {
padding-#{$side}: #{px2rem($space)} !important;
}
}
}

.flex-center {
display: flex;
align-items: center;
}

@mixin font-dpr($font-size){
font-size: $font-size;

[data-dpr=”2″] & {
font-size: $font-size * 2;
}

[data-dpr=”3″] & {
font-size: $font-size * 3;
}
}
App.vue, 使用 px2rem 进行转换
<style lang=”scss”>
@import “@/assets/style/helper.scss”;

#nav {
padding: px2rem(24);
a {
font-size: px2rem(24);
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>

正文完
 0