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

目录
[隐藏]

本文介绍的方案来源于一次 H5 活动的开发实践。 H5 DEMO 参考:bir2017

拿到设计稿后,如何进行布局还原?

如果只需要做非精确的响应式设计,那么使用媒体查询来实现就 OK 了。如果需要精确还原设计稿,则一般通过缩放来实现,常见的缩放方案有基于 viewport 和基于 rem 的布局适配方法。

1 viewport 缩放方案

在移动端,可以通过 viewport 缩放页面大小比率达到目的。

简单来说,即所有宽高像素与视觉稿输出相同,然后通过页面宽度与视觉稿的宽度比率,动态设置 viewport。缩放方案核心代码参考:

(function () {
    var docEl = document.documentElement;
    var isMobile = window.isMobile /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobi/i.test(navigator.userAgent);

    function setScale() {
        var pageScale = 1;

        if (window.top !== window) {
            return pageScale;
        }

        var width = docEl.clientWidth || 360;
        var height = docEl.clientHeight || 640;
        if (width / height >= 360 / 640) {
            // 高度优先
            pageScale = height / 640;
        } else {
            pageScale = width / 360;
        }

        var content = 'width=' + 360 + ', initial-scale=' + pageScale 
          + ', maximum-scale=' + pageScale + ', user-scalable=no';
        document.getElementById('viewport').setAttribute('content', content);

        window.pageScale = pageScale;
    }

    if (isMobile) {
        setScale();
    } else {
        docEl.className += ' pc';
    }
})()

这种方案我们在去年的一次 H5 活动页设计中进行了相关实践,详见:https://lzw.me/a/h5-myflyme.html

但是如果希望 PC 上也能显示,由于 PC 上没有 viewport 的缩放概念,只能以固定值来设定,这个效果就不太理想。

2 rem 布局适配方案

rem 布局适配方案被提到的比较多,在各大互联网企业 web 产品中都有较为广泛的应用。

简单来说其方法为:

  • 按照设计稿与设备宽度的比例,动态计算并设置 html 根标签的 font-size 大小;
  • css 中,设计稿元素的宽、高、相对位置等取值,按照同等比例换算为 rem 为单位的值;
  • 设计稿中的字体使用 px 为单位,通过媒体查询稍作调整。

下面我们举个例子来说明。

2.1 动态设置 html 标签 font-size 大小

第一个问题是 html 标签的 font-size 动态计算。

这取决于如何约定换算比例,以页面宽度 10 等份为例,核心代码参考:

(function(WIN) {
    var  setFontSize = WIN.setFontSize = function (_width) {
        var  docEl = document.documentElement; 
        // 获取当前窗口的宽度
        var  width = _width || docEl.clientWidth; // docEl.getBoundingClientRect().width;

        // 大于 1080px 按 1080
        if (width > 1080) { 
            width = 1080;
        }

        var  rem = width / 10;
        console.log(rem);

        docEl.style.fontSize = rem + 'px';

        // 部分机型上的误差、兼容性处理
        var  actualSize = win.getComputedStyle && parseFloat(win.getComputedStyle(docEl)["font-size"]);
        if (actualSize !== rem && actualSize > 0 && Math.abs(actualSize - rem) > 1) {
            var remScaled = rem * rem / actualSize;
            docEl.style.fontSize = remScaled + 'px';
        }
    }

    var timer;
    //函数节流
    function dbcRefresh() {
        clearTimeout(timer);
        timer = setTimeout(setFontSize, 100);
    }

    //窗口更新动态改变 font-size
    WIN.addEventListener('resize', dbcRefresh, false);
    //页面显示时计算一次
    WIN.addEventListener('pageshow', function(e) {
        if (e.persisted) { 
            dbcRefresh() 
        }
    }, false);
    setFontSize();
})(window)

另外,对于全屏显示的 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: 70px;。按照如上换算方式,得到该元素最终的 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 作为单位。
文字依然使用 px 为单位,然后针对性使用媒体查询设置几种大小即可。

示例参考:


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

3 相关参考

本次实践的活动项目:https://2017.flyme.cn
http://www.jianshu.com/p/dfa33d3be23c
一篇真正教会你开发移动端页面的文章

点赞 (10)
  1. 夏日博客说道:
    Google Chrome 55.0.2883.87 Google Chrome 55.0.2883.87 Windows 7 x64 Edition Windows 7 x64 Edition

    只认识一个font-size。 :smile:

    1. roc说道:
      Google Chrome 66.0.3359.139 Google Chrome 66.0.3359.139 Mac OS X  10.13.4 Mac OS X 10.13.4

      :exclaim:

  2. 123说道:
    Google Chrome 66.0.3355.4 Google Chrome 66.0.3355.4 Windows 7 Windows 7

    123

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code