Vue中750設計原稿pxが自動的にremに変換

1227 ワード

一、postcss-pxtoremをダウンロードする
実行npm install postcss-pxtoremダウンロード完了後、package.jsonファイルにこのコードを追加
"postcss": { //     
  "plugins": {
    "autoprefixer": {},
    "postcss-pxtorem": {
      "rootValue": 37.5, 
      "propList": [
      "*"
      ]
    }
  }
},
"browserslist": [ //      ,          
  "> 1%",
  "last 2 versions",
  "not ie <= 8"
]

二、プロジェクトutilsフォルダでrem.jsファイルを作成する
次のコードを追加
function setRem() {
	let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
	let htmlDom = document.querySelector('html')
	htmlDom.style.fontSize = htmlWidth / 20 + 'px'
}
setRem();
window.onresize = function () {
	setRem()
}

三、main.jsに導入
import './utils/rem.js'

モバイル側H 5ページPC側固定ビューサイズ
  • clientWidth:ブラウザウィンドウドキュメントの表示幅.
  • offsetWidth:ルートノードhtml要素オブジェクトの幅.

  • ClientWidthをoffsetWidthに変更します.vueプロジェクトのpublicフォルダのindexを見つけます.html、このファイルにhtmlラベルの後ろにstyle='max-width:750px ; margin: 0 auto'を追加します.これにより、PC側ではブラウザの幅にかかわらず、750 px幅の最大表示幅の適応スタイルしか表示されません.