前军教程网

中小站长与DIV+CSS网页布局开发技术人员的首选CSS学习平台

vue项目大屏自适应,使用postcss-px2rem插件

1、安装插件

npm install postcss-px2rem  --save

2、引入postcss.config.js文件


代码如下:

module.exports = {
    "plugins": {
        "postcss-import": {},
        "postcss-url": {},
        "postcss-aspect-ratio-mini": {}, 
        "postcss-write-svg": {
            utf8: false
        },
        "postcss-cssnext": {},
        "postcss-px-to-viewport": {
            viewportWidth: document.documentElement.clientWidth,     // (Number) The width of the viewport.
            viewportHeight: document.documentElement.clientHeight,    // (Number) The height of the viewport.
            unitPrecision: 3,       // (Number) The decimal numbers to allow the REM units to grow to.
            viewportUnit: 'vw',     // (String) Expected units.
            selectorBlackList: ['.ignore', '.hairlines'],  // (Array) The selectors to ignore and leave as px.
            minPixelValue: 1,       // (Number) Set the minimum pixel value to replace.
            mediaQuery: false       // (Boolean) Allow px to be converted in media queries.
        }, 
        "postcss-viewport-units":{},
        "cssnano": {
            preset: "advanced",
            autoprefixer: false,
            "postcss-zindex": false
        }
    }
}

3、在 vue.config.js 中添加配置

const px2rem = require('postcss-px2rem')
const postcss = px2rem({
  remUnit: 16   //基准大小 baseSize,需要和rem.js中相同
})
 
module.exports = {
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          postcss
        ]
      }
    }
  }
}

4、添加 rem.js文件

在utils目录下新建rem.js文件

// rem等比适配配置文件
// 基准大小
const baseSize = 16
    // 设置 rem 函数
function setRem() {
    // 当前页面宽度相对于 1920宽的缩放比例,可根据自己需要修改。
    const scale = document.documentElement.clientWidth / 1920 //当前设计稿为1920  如果是750则 替换为 750
        // 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
    document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
    console.log(scale, 'scalescalescale')
}
// 初始化
setRem()
window.setRem = setRem
    // 改变窗口大小时重新设置 rem
window.onresize = function() {
    setRem()
}

5、引入rem.js文件

在main.js引入rem.js文件

// 适配文件
import './utils/rem'

这样配置就完成了。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言