vue + webpack + px2rem 把px自动转为rem

在项目中px自动转为rem


第一步安装   npm install   postcss-px2rem postcss --save  

第二步  在 webpack.base.conf.js中 引入

const webpack = require('webpack')

const px2rem = require('postcss-px2rem')

const postcss = require('postcss')

第三步 在module中添加如下代码

 plugins: [
    new webpack.LoaderOptionsPlugin({
        // webpack 2.0之后, 此配置不能直接写在自定义配置项中, 必须写在此处
        vue: {
            postcss: [require('postcss-px2rem')({ remUnit: 75, propWhiteList: [] })]
        },
    })
  ],


第四步       在rules中加如下代码,css我是用到sass,所以需要引入对应的loader,不需要的可不写。

{
        test: /\.(css|less|scss)(\?.*)?$/,
        loader: 'style-loader!css-loader!sass-loader!less-loader!postcss-loader'

}


第五步:测试  加入一下css

div{
  width: 750px;
  height: 200px;
  font-size:28px;
}

到此为止,px2rem 就算配置完成了,但是要想在页面中使用,我建议还是在index.html中加入

<script>
  (function(d,f){var s=d.document;var c=s.documentElement;var m=s.querySelector('meta[name="viewport"]');var n=s.querySelector('meta[name="flexible"]');var a=0;var r=0;var b=0;var l;var e=f.flexible||(f.flexible={});if(n){var j=n.getAttribute("content");if(j){var q=j.match(/initial\-dpr=([\d\.]+)/);var h=j.match(/maximum\-dpr=([\d\.]+)/);if(q){a=parseFloat(q[1]);r=parseFloat((1/a).toFixed(2))}if(h){a=parseFloat(h[1]);r=parseFloat((1/a).toFixed(2))}}}if(!a&&!r){var p=d.navigator.appVersion.match(/android/gi);var o=d.navigator.appVersion.match(/iphone/gi);var k=d.devicePixelRatio;if(k>=3&&(!a||a>=3)){a=3}else{if(k>=2&&(!a||a>=2)){a=2}else{a=1}}r=1/a}c.setAttribute("data-dpr",a);m=s.createElement("meta");m.setAttribute("name","viewport");m.setAttribute("content","width=device-width, initial-scale="+r+", maximum-scale="+r+", minimum-scale="+r+", user-scalable=no");if(c.firstElementChild){c.firstElementChild.appendChild(m)}else{var g=s.createElement("div");g.appendChild(m);s.write(g.innerHTML)}function i(){var u=c.getBoundingClientRect().width;if(u/a>540){u=540*a}var w=u/10;c.style.fontSize=w+"px";e.rem=d.rem=w;var v=parseFloat(c.style.fontSize),t=parseFloat(window.getComputedStyle(c).getPropertyValue("font-size"));console.log("flexible.refreshRem: fontSize && finalFontSize => ",v,t);if(v!==t){c.style.fontSize=v*(v/t)+"px";console.log("flexible.refreshRem.fixed: fontSize  => ",c.style.fontSize)}}d.addEventListener("resize",function(){clearTimeout(l);l=setTimeout(i,300)},false);d.addEventListener("pageshow",function(t){if(t.persisted){clearTimeout(l);l=setTimeout(i,300)}},false);if(s.readyState==="complete"){s.body.style.fontSize=12*a+"px"}else{s.addEventListener("DOMContentLoaded",function(t){s.body.style.fontSize=12*a+"px"},false)}i();e.dpr=d.dpr=a;e.refreshRem=i;e.rem2px=function(u){var t=parseFloat(u)*this.rem;if(typeof u==="string"&&u.match(/rem$/)){t+="px"}return t};e.px2rem=function(u){var t=parseFloat(u)/this.rem;if(typeof u==="string"&&u.match(/px$/)){t+="rem"}return t}})(window,window["lib"]||(window["lib"]={}));
</script>

如果你的运行页面如下,就可以直接使用750设计图里面的真实PX值就可以啦




嘿嘿,上面是使用px2rem来做的适配,还有一种方式以sass为基础的适配效果

在index.html中

<script>
  (function(d,f){var s=d.document;var c=s.documentElement;var m=s.querySelector('meta[name="viewport"]');var n=s.querySelector('meta[name="flexible"]');var a=0;var r=0;var b=0;var l;var e=f.flexible||(f.flexible={});if(n){var j=n.getAttribute("content");if(j){var q=j.match(/initial\-dpr=([\d\.]+)/);var h=j.match(/maximum\-dpr=([\d\.]+)/);if(q){a=parseFloat(q[1]);r=parseFloat((1/a).toFixed(2))}if(h){a=parseFloat(h[1]);r=parseFloat((1/a).toFixed(2))}}}if(!a&&!r){var p=d.navigator.appVersion.match(/android/gi);var o=d.navigator.appVersion.match(/iphone/gi);var k=d.devicePixelRatio;if(k>=3&&(!a||a>=3)){a=3}else{if(k>=2&&(!a||a>=2)){a=2}else{a=1}}r=1/a}c.setAttribute("data-dpr",a);m=s.createElement("meta");m.setAttribute("name","viewport");m.setAttribute("content","width=device-width, initial-scale="+r+", maximum-scale="+r+", minimum-scale="+r+", user-scalable=no");if(c.firstElementChild){c.firstElementChild.appendChild(m)}else{var g=s.createElement("div");g.appendChild(m);s.write(g.innerHTML)}function i(){var u=c.getBoundingClientRect().width;if(u/a>540){u=540*a}var w=u/10;c.style.fontSize=w+"px";e.rem=d.rem=w;var v=parseFloat(c.style.fontSize),t=parseFloat(window.getComputedStyle(c).getPropertyValue("font-size"));console.log("flexible.refreshRem: fontSize && finalFontSize => ",v,t);if(v!==t){c.style.fontSize=v*(v/t)+"px";console.log("flexible.refreshRem.fixed: fontSize  => ",c.style.fontSize)}}d.addEventListener("resize",function(){clearTimeout(l);l=setTimeout(i,300)},false);d.addEventListener("pageshow",function(t){if(t.persisted){clearTimeout(l);l=setTimeout(i,300)}},false);if(s.readyState==="complete"){s.body.style.fontSize=12*a+"px"}else{s.addEventListener("DOMContentLoaded",function(t){s.body.style.fontSize=12*a+"px"},false)}i();e.dpr=d.dpr=a;e.refreshRem=i;e.rem2px=function(u){var t=parseFloat(u)*this.rem;if(typeof u==="string"&&u.match(/rem$/)){t+="px"}return t};e.px2rem=function(u){var t=parseFloat(u)/this.rem;if(typeof u==="string"&&u.match(/px$/)){t+="rem"}return t}})(window,window["lib"]||(window["lib"]={}));
</script>

sass文件中

$browser-default-font-size: 37.5px !default;
//$browser-default-font-size: 75px !default;

@function pxTorem($px){//$px为需要转换的字号
    @if (unitless($px)) {
        @return pxTorem($px + 0px);
    }@else if (unit($px) == em) {
        @return $px;
    }
    @return ($px / $browser-default-font-size) * 1rem;
}

vue文件中使用




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue项目中使用postcss-pxtorem插件可以将px单位换为rem单位。以下是使用步骤: 1. 首先,确保你已经安装了postcss和postcss-pxtorem插件。可以通过以下命令进行安装: ``` npm install postcss postcss-pxtorem --save-dev ``` 2. 在项目根目录下创建一个postcss.config.js文件,并在该文件中配置postcss-pxtorem插件。示例配置如下: ```javascript module.exports = { plugins: { 'postcss-pxtorem': { rootValue: 16, // rem基准值,通常为设计稿宽度的1/10或1/16 propList: ['*'], // 需要换的属性,*表示所有属性 selectorBlackList: [] // 需要忽略的选择器,比如引入第三方UI库时需要排除 } } } ``` 3. 在项目的build/webpack.base.conf.js文件中的postcss-loader配置中添加postcss-pxtorem插件。示例配置如下: ```javascript const px2remConfig = { loader: 'postcss-loader', options: { sourceMap: true, config: { path: 'postcss.config.js' // 指定postcss配置文件路径 } } } module.exports = { // ... module: { rules: [ // ... { test: /\.css$/, use: [ 'vue-style-loader', 'css-loader', px2remConfig // 添加postcss-pxtorem插件 ] }, // ... ] }, // ... } ``` 4. 配置完成后,重新启动项目,此时px单位会自动换为rem单位。 需要注意的是,postcss-pxtorem插件会将所有px单位换为rem单位,如果你希望某些特定的属性不进行换,可以在配置文件中的propList选项中添加对应的属性名。另外,如果你使用了第三方UI库,可能需要在配置文件的selectorBlackList选项中添加相应的选择器来排除换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YaoZhanHui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值