详解H5 活动页之移动端 REM 布局适配方法

2019-01-28 12:58:17王振洲

另外,对于全屏显示的 H5 活动页,对宽高比例有所要求,此时应当做的调整。可以这么来做:

function adjustWarp(warpId = '#warp') { // if (window.isMobile) return; const $win = $(window); const height = $win.height(); let width = $win.width(); // 考虑导航栏情况 if (width / height < 360 / 600) { return; } width = Math.ceil(height * 360 / 640); $(warpId).css({ height, width, postion: 'relative', top: 0, left: 'auto', margin: '0 auto' }); // 重新计算 rem window.setFontSize(width); }

按照这种缩放方法,几乎在任何设备上都可以实现等比缩放的精确布局。

2.2 元素大小取值方法

第二个问题是元素大小的取值。

以设计稿宽度 1080px 为例,我们将宽度分为 10 等份以便于换算,那么 1rem = 1080 / 10 = 108px 。其换算方法为:

const px2rem = function(px, rem = 108) { let remVal = parseFloat(px) / rem; if (typeof px === "string" && px.match(/px$/)) { remVal += 'rem'; } return remVal; }

例如,设计稿中有一个图片大小为 460x210 ,相对页面位置 top: 321px; left: 70; 。按照如上换算方式,得到该元素最终的 css 样式应为:

.img_demo { position: absolute; background-size: cover; background-image: url('demo.png'); top: 2.97222rem; left: 0.64814rem; width: 4.25926rem; height: 1.94444rem; }

2.3 rem 布局方案的开发方式

通过以上方法,rem 布局方案就得到了实现。但是手动计算 rem 的取值显然不现实。

通过 less/sass 预处理工具,我们只需要设置 mixins 方法,然后按照设计稿的实际大小来取值即可。以 less 为例,mixins 参考如下:

// px 转 rem .px2rem(@px, @attr: 'width', @rem: 108rem) { @{attr}: (@px / @rem); } .px2remTLWH(@top, @left, @width, @height, @rem: 108rem) { .px2rem(@top, top, @rem); .px2rem(@left, left, @rem); .px2rem(@width, width, @rem); .px2rem(@height, height, @rem); }

针对前文的示例元素,css 样式可以这样来写:

.img_demo { position: absolute; background-size: cover; background-image: url('demo.png'); .px2remTLWH(321, 70, 460, 210); }

这里,宽和高可以直接通过设计稿输出的图片元素大小读取到;top/left 的取值,可以通过在 Photoshop 中移动参考线定位元素快速得到。

2.4 字体使用 px 为单位

字体使用 rem 等比缩放会出现显示上的问题,只需要针对性使用媒体查询设置几种大小即可。

示例参考:

// 字体响应式 @media screen and (max-width: 321px) { body { font-size: 13px; } } @media screen and (min-width: 321px) and (max-width: 400px) { body { font-size: 14px; } } @media screen and (min-width: 400px) { body { font-size: 16px; } }