rem的随笔

70 阅读1分钟
  1. 自调用函数(写在index.html的一个script标签下即可)
(function (doc, win, undefined) {
      var docEl = doc.documentElement,
        resizeEvt =
          "orientationchange" in win ? "orientationchange" : "resize",
        recalc = function () {
          var clientWidth = docEl.clientWidth;
          if (clientWidth === undefined) return;
          docEl.style.fontSize = 16 * (clientWidth / 1280) + "px";
        };
      if (doc.addEventListener === undefined) return;
      win.addEventListener(resizeEvt, recalc, false);
      doc.addEventListener("DOMContentLoaded", recalc, false);
    })(document, window);
  1. 安装 postcss-pxtorem
npm i -D postcss-pxtorem
  1. 编辑postcss.config.js
module.exports = {
  plugins: {
    'autoprefixer': {
    },
    'postcss-pxtorem': {
      // 与自调用函数处 保持一致即可 docEl.style.fontSize = 16 * (clientWidth / 1280) + "px";
      rootValue: 16,//结果为:设计稿元素尺寸/16,比如元素宽320px,最终页面会换算成 20rem
      propList: ['*']
    }
  }
}