web移动端自适应vw、vh、rem

vw+vh+rem

一、vw、vh

  vw、vh是基于视口的布局方案,故这个meta元素的视口必须声明。(视口宽度等于设备宽度,初始不缩放,用于解决页面宽高自动适配屏幕)

 <meta name="viewport" content="width=device-width,initial-scale=1.0">

  1vw等于设备宽度的1%,同理1vh等于设备高度的1%,百分比布局

  px转vw

  https://developer.aliyun.com/mirror/npm/package/postcss-px-to-viewport

npm install postcss-px-to-viewport --save-dev
// postcss.config.js
module.exports = {
  plugins: {
    autoprefixer: {},
    'postcss-px-to-viewport': {
      viewportWidth: 375, // 视窗的宽度,对应的是我们设计稿的宽度,一般是750
      // viewportHeight: 1334, // 视窗的高度,根据750设备的宽度来指定,一般指定1334,也可以不配置
      unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数(很多时候无法整除)
      viewportUnit: 'vw', // 指定需要转换成的视窗单位,建议使用vw
      selectorBlackList: ['.ignore', '.hairlines'], // 指定不转换为视窗单位的类,可以自定义,可以无限添加,建议定义一至两个通用的类名
      minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值
      mediaQuery: false // 允许在媒体查询中转换`px`
    },
    'postcss-viewport-units': {
      // 排除会产生警告的部份
      filterRule: rule => rule.nodes.findIndex(i => i.prop === 'content') === -1
    },
    cssnano: {
      preset: 'advanced',
      autoprefixer: false, // 和autoprefixer同样具有autoprefixer,保留一个
      'postcss-zindex': false
    }
  }
}

二、rem

  相对单位,根据CSS的媒体查询功能,更改html根字体大小,实现字体大小随屏幕尺寸变化。

  举例:浏览器默认html的字体大小为16px,则1rem=16px

三、rem配置(方式1)

  px自动转换rem,postcss-pxtorem

  github:GitHub - cuth/postcss-pxtorem: Convert pixel units to rem (root em) units using PostCSS

npm install postcss-pxtorem -D

   自动转换设置(vue-cli3)

// postcss.config.js
module.exports = {
  plugins: {
    autoprefixer: {},
    'autoprefixer': {
      browsers: ['Android >= 4.0', 'iOS >= 7']
    },
    'postcss-pxtorem': {
      rootValue: 10,// 转换1rem=10px
      propList: ['*']
    }
  }
}

四、rem配置(方式2)

  更多详情可参考:移动端适配方案 - OSCHINA - 中文开源技术交流社区

  1. lib-flexible,手淘开发,用于适配移动端的开源库

  安装lib-flexible

    github:GitHub - amfe/lib-flexible: 可伸缩布局方案

npm install lib-flexible --save-dev
npm install px2rem-loader --save-dev

  2. 引入(vue)

// main.js
import 'lib-flexible'

  3. 配置(vue-cli3.0)

// vue.config.js
module.exports = {
    css: {
        loaderOptions: {
            css: {},
            postcss: {
                plugins: [
                    require('postcss-px2rem')({
                        // 以设计稿750为例, 750 / 10 = 75
                        remUnit: 75
                    }),
                ]
            }
        }
    },
};

  4. 修改最大适配尺寸

  依赖包中打开./node_modules/lib-flexible/flexible.js

// ./node_modules/lib-flexible/flexible.js 
// 找到该方法,默认最大适配尺寸为540px,修改540为需要值,重新运行项目即可
   function refreshRem(){
        var width = docEl.getBoundingClientRect().width;
        if (width / dpr > 540) {
            width = 540 * dpr;
        }
        var rem = width / 10;
        docEl.style.fontSize = rem + 'px';
        flexible.rem = win.rem = rem;
    }

 五、rem配置(方式3)rem.js

  参考:使用rem.js快速进行移动端适配 - 简书

   两个参数分别是designWidth 和maxWidth,顾名思义,就是我们设计稿的宽度和我们设定的最大宽度

   main.js中引入rem.js(vue)

// rem.js
(function (designWidth, maxWidth) {
    var doc = document,
        win = window;
    var docEl = doc.documentElement;
    var tid;
    var rootItem, rootStyle;

    function refreshRem() {
        var width = docEl.getBoundingClientRect().width;
        console.log(width,"width",maxWidth,"maxWidth")
        if (!maxWidth) {
            maxWidth = 540;
        }
        ;
        if (width > maxWidth) {
            width = maxWidth;
        }
        //与淘宝做法不同,直接采用简单的rem换算方法1rem=10px,与上面rootValue应该保持一致
        var rem = width * 10 / designWidth;
        //兼容UC开始
        rootStyle = "html{font-size:" + rem + 'px !important}';
        rootItem = document.getElementById('rootsize') || document.createElement("style");
        if (!document.getElementById('rootsize')) {
            document.getElementsByTagName("head")[0].appendChild(rootItem);
            rootItem.id = 'rootsize';
        }
        if (rootItem.styleSheet) {
            rootItem.styleSheet.disabled || (rootItem.styleSheet.cssText = rootStyle)
        } else {
            try {
                rootItem.innerHTML = rootStyle
            } catch (f) {
                rootItem.innerText = rootStyle
            }
        }
        //兼容UC结束
        docEl.style.fontSize = rem + "px";
    };
    refreshRem();

    win.addEventListener("resize", function () {
        clearTimeout(tid); //防止执行两次
        tid = setTimeout(refreshRem, 300);
    }, false);

    win.addEventListener("pageshow", function (e) {
        if (e.persisted) { // 浏览器后退的时候重新计算
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }
    }, false);

    // if (doc.readyState === "complete") {
    //     doc.body.style.fontSize = "32px";
    // } else {
    //     doc.addEventListener("DOMContentLoaded", function (e) {
    //         doc.body.style.fontSize = "32px";
    //     }, false);
    // }
})(375, 750);

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用`node-sass`和`sass-loader`来解析`.scss`文件,同时使用`postcss-loader`和`autoprefixer`来自动添加浏览器厂商前缀,最后使用`css-loader`和`style-loader`将CSS样式注入到HTML页面中。 在Vue项目中,可以在`vue.config.js`文件中进行配置: ```javascript module.exports = { css: { loaderOptions: { sass: { prependData: ` @import "@/assets/scss/_variables.scss"; @import "@/assets/scss/_mixins.scss"; ` }, postcss: { plugins: [ require('autoprefixer')({ overrideBrowserslist: ['last 2 versions', '>1%'] }) ] } } } } ``` 然后,可以在`.vue`文件中使用`<style lang="scss">`标签来编写Sass样式,例如: ```scss // _variables.scss $base-font-size: 16px; $base-width: 750px; // _mixins.scss @function px2rem($px) { @return ($px / $base-font-size) * 1rem; } @mixin center() { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } // index.vue <style lang="scss"> .container { width: $base-width; margin: 0 auto; } .title { font-size: px2rem(32px); margin-top: px2rem(20px); } .box { width: 50vw; height: 50vh; background-color: #f00; @include center(); } </style> <template> <div class="container"> <h1 class="title">Hello World!</h1> <div class="box"></div> </div> </template> ``` 以上示例中,`$base-font-size`和`$base-width`变量定义在`_variables.scss`中,`px2rem()`和`center()`混合宏定义在`_mixins.scss`中,然后在`index.vue`中引入并使用它们来实现移动端自适应布局。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值