美文网首页
vue移动端布局单位适配(postcss)

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

作者: 独自迈向前方 | 来源:发表于2021-03-19 19:17 被阅读0次

    一、需要解决的问题

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

    二、rem单位与适配原理

    • px、em、rem区别介绍
    • rem单位不是固定大小的,会根据html标签的font-size大小决定实际大小。例:<html stytle="font-size:16px">时,1rem == 16px
    • 所以分两步解决:
      • 1)、将所有px单位转换为rem
      • 2)、根据不同设备的屏幕大小改变html的字体大小

    三、适配代码

    • 转换px单位:
    // 安装postcss-pxtorem转换库
    // 如果是vue3.* 后续可能会报错,提示postcss使用^8.0版本,请使用postcss-plugin-px2rem库替换
    npm install postcss-pxtorem --save-dev
    
    • postcss-pxtorem库的webpack使用配置
    // ./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)
                        }),
                    ]
                }
            }
        },
    }
    
    
    
    
    • 编写自动根据屏幕大小动态设置html的字体大小的js
      • 下列代码主要是根据窗口大小变换,自动设置html的font-size,保证再任何大小,单位相对一致
    // ./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))
    
    
    
    • 在入口文件main.ts中引入flexible.ts
    import "./utils/flexible"
    

    四、具体转换参考实例

    实例

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

    • 待定

    相关文章

      网友评论

          本文标题:vue移动端布局单位适配(postcss)

          本文链接:https://www.haomeiwen.com/subject/lelbcltx.html