九、響應式發:rem和less(適配移動端)


一、響應式開發

響應式開發優先適配移動端又兼容到pc端
官網:https://less.bootcss.com/usage/
教程:https://www.w3cschool.cn/less/
rem和em:https://blog.csdn.net/u010132177/article/details/103725945
參考:https://www.jianshu.com/p/58a061c6e9af

1.1安裝less依賴

cnpm install less less-loader --save-dev
//記錄到devDependencies中,因為這是我們在開發中使用的而非在生產中使用(當然,也可以不加--save-dev)

1.1.2 安裝 style-loader、css-loader

cnpm install --save-dev style-loader css-loader

【待整理】=====================

1.2 添加配置到 build/webpack.base.conf.js

【配置】

,{   //加less配置開始
      test: /\.less$/,
      use: [
        "style-loader",
        "css-loader",
        "less-loader"
      ]
    }//加less配置結尾
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }, {//【配置】加less配置開始
      test: /\.less$/,
      use: [
        "style-loader",
        "css-loader",
        "less-loader"
      ]
    }//加less配置結尾]
  },

  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

1.3 在根目錄 index.html下添加代碼:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css">
    <title>hello_vue</title>
  <script>
     (function (doc, win) {
      var docEl = doc.documentElement,
      resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
      recalc = function () {
          var clientWidth = docEl.clientWidth;
          if (!clientWidth) return;
          if(clientWidth>=750){
              docEl.style.fontSize = '100px';
          }else{
              docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
          }
      };

      if (!doc.addEventListener) return;
      win.addEventListener(resizeEvt, recalc, false);
      doc.addEventListener('DOMContentLoaded', recalc, false);
      })(document, window);
  </script>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

代碼解釋:

<1>設置meta屬性  <meta name="viewport" content="width=device-width,initial-scale=1.0">
<script>
<2>運用rem特性進行寬度適配
   (function(){
    let html = document.documentElement,
    hWidth = html.getBoundingClientRect().width;
    console.log(hWidth);
    html.style.fontSize = hWidth/15 + "px";//1rem的長度
    })()//根據設計圖進行設計,所有的頁面完成必須是基於同一個設備或者說是同一分辨率的設備,比如上面代碼中的15是可以根據你所選設備的分辨率自行進行選擇,最后讓font-size為5的倍數,上面代碼的核心是保證在不同的設備分辨率下可以動態的調整rem(1rem 就等於 html的font-size)
<3>使用less或者是sass進行css開發,我是基於vue庫進行開發的,所以進行如下操作引入less編譯器
npm install less less-loader --save//下載less編譯器
   {
        test: /\.less$/,
        loader: "style-loader!css-loader!less-loader",
      }//在webpack.base.conf.js 中的module模塊中加入這都代碼
<4> vue中使用less
<style lange="less">
 @rem:25rem //這個值是如何確定的?比如我一開始的屏幕分辨率是基於iphone6 其中寬度為375px,所以此時我設置的font-size :375/15,即此時1rem為25px,所以我此時設置這個變量為25,看下面我對css變量的設置
.main{
     width:280/@rem;//此時如果換在iphone6上面,在設計圖上該樣式的寬度為280px,這個是固定寬度,不能進行適配,所以我需要將其轉尺寸換為rem來表示 此時@rem代表的是你的font-size尺寸(全套頁面必須基於同一個設備分辨率來完成)即1rem, 所以280px對應的rem為280/@rem?
}

</style>
<script>
//使用原生js進行設備的適配
(function flexible (window, document) {
  var docEl = document.documentElement
  var dpr = window.devicePixelRatio || 1

  // adjust body font size
  function setBodyFontSize () {
    if (document.body) {
      document.body.style.fontSize = (12 * dpr) + 'px'
    }
    else {
      document.addEventListener('DOMContentLoaded', setBodyFontSize)
    }
  }
  setBodyFontSize();

  // set 1rem = viewWidth / 10
  function setRemUnit () {
    var rem = docEl.clientWidth / 10
    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()
    }
  })

  // detect 0.5px supports
  if (dpr >= 2) {
    var fakeBody = document.createElement('body')
    var testElement = document.createElement('div')
    testElement.style.border = '.5px solid transparent'
    fakeBody.appendChild(testElement)
    docEl.appendChild(fakeBody)
    if (testElement.offsetHeight === 1) {
      docEl.classList.add('hairlines')
    }
    docEl.removeChild(fakeBody)
  }
}(window, document))
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM