vue移动端布局单位适配(postcss)

2021-03-19  本文已影响0人  独自迈向前方

一、需要解决的问题

不同设备看到的视觉效果不同 适配修正后的

二、rem单位与适配原理

三、适配代码

// 安装postcss-pxtorem转换库
// 如果是vue3.* 后续可能会报错,提示postcss使用^8.0版本,请使用postcss-plugin-px2rem库替换
npm install postcss-pxtorem --save-dev
// ./vue.config.js
module.exports = {
    css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    // require('postcss-pxtorem')({
                    require('postcss-plugin-px2rem')({
                        rootValue: 16, // 这个值为16,因为浏览器的默认字体为大小为16。具体说明查看./src/utils/flexible.ts
                        selectorBlackList: ['#app', '.px-', 'html', 'body'], // 忽略的.px-前缀的类、#app、html和body标签
                        propBlackList: ['border'], // 忽略border前缀的属性(postcss-plugin-px2rem 存在该属性)
                        // propList: ['*', '!border'] // postcss-pxtorem请使用该属性(效果同上propBlackList)
                    }),
                ]
            }
        }
    },
}



// ./src/utils/flexible.ts
(function flexible(window: Window, document: Document) {
    let docEl: HTMLElement = document.documentElement;
    // let dpr: number = window.devicePixelRatio || 1;

    // 设计稿宽度 / rootValue  => 750 / 16 = 45 => 即可保证在所有视口下 1rem === 16px。bisection是与postcss-pxtorem中的rootValue 关联的
    // 既:1rem === 设计稿宽度 / bisection === rootValue
    const bisection: number = 45; 


    function setRemUnit() {
        const viewWidth = docEl.clientWidth || document.body.clientWidth;
        const rem = viewWidth / bisection;
        docEl.style.fontSize = rem + 'px'
    }

    setRemUnit()

    // reset rem unit on page resize
    window.addEventListener('resize', setRemUnit)
    window.addEventListener('pageshow', function (e) {
        if (e.persisted) {
            setRemUnit()
        }
    })
}(window, document))


import "./utils/flexible"

四、具体转换参考实例

实例

五、移动端整体最大宽度限定(进阶)

上一篇下一篇

猜你喜欢

热点阅读