移动端-适配方案

移动端-适配方案

1. 安装依赖

npm install px2rem-loader  lib-flexible --save 

2. 设置viewport

设置: <meta name="viewport" content="width=device-width,initial-scale=1.0">
  1. 说明: 因为默认的布局视口大于视觉视口,如果不设置将导致页面的内容显示非常小
  2. 原理: 将980的页面在375的屏幕上完全显示只能缩小980页面中的内容

3. 直接设置px问题

1. px为css像素单位等同于独立设备像素单位
2. 设计师给的设计稿的单位是物理像素单位
3. 直很多设备上接设置px像素单位会比设计师的要求大

4. Vue2中使用px2rem, lib-flexible

1. 在项目入口文件 main.js 里 引入 lib-flexible, flexible会自动根据设备情况动态设置rem的值的大小

import 'lib-flexible/flexible'

2. 在build文件夹下的util.js中添加


// 全局定义px2remLoader
const px2remLoader = {
    loader: 'px2rem-loader',
    options: {
    remUnit: 37.5  // remUnit为转换rem的基础 设计稿单位/等分数 = remUnit
    }
}
    // 在该函数的loaders中添加
     function generateLoaders (loader, loaderOptions) {
         // 添加使用 px2remLoader
         const loaders = options.usePostCSS ? [cssLoader, postcssLoader,px2remLoader] : [cssLoader, px2remLoader]


    if (loader) {
    loaders.push({
    loader: loader + '-loader',
    options: Object.assign({}, loaderOptions, {
    sourceMap: options.sourceMap
    })
    })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
    return ExtractTextPlugin.extract({
    use: loaders,
    fallback: 'vue-style-loader'
    })
    } else {
    return ['vue-style-loader'].concat(loaders)
    }
}

5. Vue3中使用px2rem

  1. 安装依赖: npm install lib-flexible postcss-plugin-px2rem

  2. 在项目入口文件 main.js 里 引入 lib-flexible, flexible会自动根据设备情况动态设置rem的值的大小

    import 'lib-flexible/flexible'
    
  3. 配置内容: vue.config.js中

    css: {
    loaderOptions: {
    postcss: {
    plugins: [
    require(‘postcss-plugin-px2rem’)({
    rootValue:75, // 设置转换基数,会自动根据该 基数进行rem值转换,如设置75,页面写入高度175px 则== 1775/75rem,该值通常根据设计稿等分数进行计算,使用淘宝方案等分就是10份
    mediaQuery: false, //(布尔值)允许在媒体查询中转换px。
    minPixelValue: 3, //设置要替换的最小像素值(3px会被转rem)。 默认 0
    exclude: /(node_module)/, // 排除指定的包,不对其进行转换,通常用于指定第三方包,默认为false
    }),
    ]
    }
    }
    },

    1. 扩展: 使用lib-flexible可以实现自动根据屏幕大小不同计算rem的值
      1. 淘宝适配方案: 屏幕10等分
      2. npm install lib-flexible
      3. 在入口文件main.js中引入 import ‘lib-flexible/flexible’

6. 原生实现

  let timeoutId;
  window.addEventListener('pageshow', function () {
    refreshRem()
  })
  window.addEventListener('resize', function () {

    if(timeoutId){
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(function () {
      refreshRem()
    }, 300)
  })

  function refreshRem() {
    // 获取屏幕的宽度
    let clientWidth = document.documentElement.clientWidth;
    // 将屏幕宽度10等分
    let fontValue = clientWidth / 10;
    // 获取屏幕的设备像素比dpr的值
    let dpr = window.devicePixelRatio;
    // 确定dpr的值
    if(dpr >= 3){
      dpr = 3;
    }else if(dpr < 3 && dpr >=2){
      dpr = 2;
    }else {
      dpr = 1;
    }
    // 设定单位rem值的大小
    let rem = fontValue;

    // px转换rem的基础, 
    let remUnit = fontValue * dpr;
    // 设定body标签字体大小
    document.body.style.fontSize = '12px';
    // 设定html上fontsize的大小
    document.documentElement.style.fontSize = rem + 'px';
  }

React适配

安装依赖

1. npm install postcss-px2rem-exclude  lib-flexible --save 
2. 在入口文件中引入lib-flexible: import 'lib-flexible/flexible'

暴露React配置

1. npm run eject: 注意使用脚手架重新初始化一个项目
2. 暴露配置后如果启动不了项目就删除项目根目录下的.git文件
3. 如果丢包需要重新npm install安装所有依赖

postcss-px2rem-exclude配置

1. 原有的sass配置
    const sassRegex = /\.(scss|sass)$/;
    const sassModuleRegex = /\.module\.(scss|sass)$/;
  
    {
      test: sassRegex,
      exclude: sassModuleRegex,
      use: getStyleLoaders(
        {
          importLoaders: 2,
          sourceMap: isEnvProduction && shouldUseSourceMap,
        },
        'sass-loader'
      ),
      // Don't consider CSS imports dead code even if the
      // containing package claims to have no side effects.
      // Remove this when webpack adds a warning or an error for this.
      // See https://github.com/webpack/webpack/issues/6571
      sideEffects: true,
    },
    // Adds support for CSS Modules, but using SASS
    // using the extension .module.scss or .module.sass
    {
      test: sassModuleRegex,
      use: getStyleLoaders(
        {
          importLoaders: 2,
          sourceMap: isEnvProduction && shouldUseSourceMap,
          modules: true,
          getLocalIdent: getCSSModuleLocalIdent,
        },
        'sass-loader'
      ),
    },
  1. stylus配置,参照内置的sass配置即可

    const stylusRegex = /\.(styl|stylus)$/;
    const stylusModuleRegex = /\.module\.(styl|stylus)$/;
    {
      test: stylusRegex,
      exclude: stylusModuleRegex,
      use: getStyleLoaders(
        {
          importLoaders: 2,
          sourceMap: isEnvProduction && shouldUseSourceMap,
        },
        'stylus-loader'
      ),
      // Don't consider CSS imports dead code even if the
      // containing package claims to have no side effects.
      // Remove this when webpack adds a warning or an error for this.
      // See https://github.com/webpack/webpack/issues/6571
      sideEffects: true,
    },
    { 
      test: stylusModuleRegex, 
      use: getStyleLoaders(
        {
          importLoaders: 2,
          sourceMap: isEnvProduction && shouldUseSourceMap,
          modules: true,
          getLocalIdent: getCSSModuleLocalIdent,
        },
        'stylus-loader'
      ),
      // loaders: ['style-loader', 'css-loader', 'stylus-loader'], 
    
    },
    
  2. postcss-px2rem-exclude配置: 在postcss-loader中

    {
      // Options for PostCSS as we reference these options twice
      // Adds vendor prefixing based on your specified browser support in
      // package.json
      loader: require.resolve('postcss-loader'),
      options: {
        // Necessary for external CSS imports to work
        // https://github.com/facebook/create-react-app/issues/2677
        ident: 'postcss',
        plugins: () => [
          require('postcss-flexbugs-fixes'),
          require('postcss-preset-env')({
            autoprefixer: {
              flexbox: 'no-2009',
            },
               stage: 3,
      }),
      // Adds PostCSS Normalize as the reset css with default options,
      // so that it honors browserslist config in package.json
      // which in turn let's users customize the target behavior as per their needs.
      postcssNormalize(),
      px2rem({
        remUnit:75,exclude: /node_modules/i
      }),
    
    ],
    
    sourceMap: isEnvProduction && shouldUseSourceMap,
        
          },
        }
    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值