rem+postcss-pxtorem实现移动端响应式布局

568 阅读1分钟
"postcss-pxtorem": "^5.1.1"

vue.config.js中配置插件

module.exports = {

  productionSourceMap: process.env.NODE_ENV !== 'production', // 为false,浏览器就不会展示源文件

  css: {

    sourceMap: process.env.NODE_ENV !== 'production', // 是否为 CSS 开启 source map

    loaderOptions: {

      postcss: {

        plugins: [

          // 把px单位换算成rem单位

          require('postcss-pxtorem')({

            rootValue: 100, // 换算的基数(设计图750的根字体为32)

            selectorBlackList: ['.triangle', '.ignore_doc', '.ignore_doc_footer', '.ignore_indexBar', '.ignore_doc_num', '.ignore_swiper__item', '.ignore_height__76'], // 要忽略的选择器并保留为px。

            propList: ['*'], // 可以从px更改为rem的属性。

            minPixelValue: 0 // 设置要替换的最小像素值。

          })

        ]

      },

    }

  },

}

rem.js

// 设置 rem 函数

function setRem() {

  const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth

  // 得到html的Dom元素

  const htmlDom = document.getElementsByTagName('html')[0]

  // 设置根元素字体大小(基于414的宽度)

  htmlDom.style.fontSize = htmlWidth / 4.14 + 'px'

}

// 初始化

setRem()

// 改变窗口大小时重新设置 rem

// eslint-disable-next-line space-before-function-paren

window.onresize = function () {

  setRem()

}

基于设计图414,如果是375可以将根元素大小设置为

htmlDom.style.fontSize = htmlWidth / 3.75 + 'px'