H5页面适配

219 阅读1分钟

1.适配原理

基于1rem === 文档根元素html的fontSize大小

2.说说如何根据视图大小设置根元素html的fontSize

以375屏幕为基准改变fontSize;如下:

`(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 = (clientWidth / 3.75) + 'px';
    };

    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);

})(document, window);`

当然也可以引入插件: npm install amfe-flexible --save代替

3.使用pxtorem插件进行转换

安装npm install postcss-pxtorem --save-dev 在postcss配置里设置如下:

postcss: {
    plugins: [
        pxtorem({
            rootValue: 37.5,
            propList: ['*']
        })
    ]
}

为了兼容各个浏览器中样式补全,需要引入autoprefixer进行补全,代码如下

const autoprefixer = require('autoprefixer')
const pxtorem = require('postcss-pxtorem')
postcss: {
    plugins: [
        pxtorem({
            rootValue: 37.5,
            propList: ['*']
        })
    ]
}

4.img标签套层父元素size安装设计搞标准写入,img的宽高保持100%