H5移动端rem布局方案实现

项目入口文件,通常是index.html,加上以下代码:css

function implementRem(obj) {
    var window = obj.window || this,
    width = obj.width || 720,
    docEl = window.document.documentElement,
    dpr = window.devicePixelRatio || 1,
    resizeEvt = 'resize',
    resizeCall = (function () {
        var clientWidth = docEl.clientWidth;
        if (!clientWidth) {
            docEl.style.fontSize = 100 + 'px';
        } else {
            docEl.style.fontSize = 100 * (clientWidth / width) + 'px';
        }
          return arguments.callee;
    })();

    dpr = dpr >= 3 ? 3 : dpr >= 2 ? 2 : 1;
    docEl.setAttribute('data-dpr', dpr);
    window.addEventListener && window.addEventListener(resizeEvt, resizeCall, false);
}
implementRem({
    window: this,
    width: 720
})
复制代码

传window的做用是,服务端渲染的话,node层是拿不到window对象的,防止js报错 html

css或者less文件,书写形式以下:node

.zLog__title {
  margin: 0.7rem auto 0.47rem;
  font-size: 0;
  text-indent: 0.02rem;
  width: 5.64rem;
  height: 0.48rem;
  background-image: none;
  position: relative;
}
复制代码

若是以为css里面用rem布局开发很不习惯,或者公司ui设计稿都是基于蓝湖的话,用原来的px布局可能效率会更高一些,能够在项目里添加postcss-px2rem插件bash

css: {
    loaderOptions: {
      postcss: {
        plugins: [
          require('postcss-px2rem')({ remUnit: 100 }) // 换算的基数
        ]
      }
    }
}
复制代码

css或者less文件,书写形式以下less

.zLog__title {
    margin: 70px auto 47px;
    font-size: 0;
    text-indent: 2px;
    width: 564px;
    height: 46px;
    background-image: none;
    position: relative;
}
复制代码

边框border不少状况下都是1px,1px通过换算后,部分机型的border就达不到1px,就看不到border了,这个时候须要针对1px的css行尾 加上 no ,禁止rem的转换布局

.grade-item {
    width: 46.77%;
    height: 80px;
    background: rgba(255,255,255,1);
    border: 1px solid #FF4700; /*no*/
    border-radius: 10px;
    font-size: 28px;
    color: #FF4700;
}
复制代码

写的比较粗糙,欢迎批评指正 😎post

相关文章
相关标签/搜索