vue項(xiàng)目中使用rem,在入口文件添加內(nèi)容操作
在使用vue-cli搭建好項(xiàng)目框架后,在目錄結(jié)構(gòu)的index.html文件中添加一段js代碼:
<script> window.onload = function () { var setRem = function () { // UI設(shè)計(jì)稿的寬度 var uiWidth = 1200; // 移動(dòng)端屏幕寬度 var winWidth = document.documentElement.clientWidth; // 比率 var rate = winWidth / uiWidth; // 設(shè)置html元素的字體大小 document.documentElement.style.fontSize = rate * 20 + 'px' }; setRem(); window.onresize = function () { setRem(); }}</script>
然后在寫(xiě)css就可以將px單位換成rem.
這里設(shè)置的比例是20px=1rem,
例如:寬度為100px時(shí),可以直接寫(xiě)成5rem
(function (doc, win) { let fn = () => { let docEl = doc.documentElement, clientWidth = docEl.clientWidth; if (!clientWidth) return; docEl.style.fontSize = 16 * (clientWidth / 1920) + ’px’; } if (!doc.addEventListener) return; win.addEventListener(’resize’, fn); doc.addEventListener(’DOMContentLoaded’, fn); })(document, window);
補(bǔ)充知識(shí):vue 中使用 rem 布局的兩種方法
在使用 vue-cli 開(kāi)發(fā) H5 項(xiàng)目時(shí),需要進(jìn)行 rem 適配,下面提供兩種常用的方法(以 750 設(shè)計(jì)稿為例),希望對(duì)大家有所幫助。
方法一:在 index.html 或者 main.js 中添加以下代碼:
const setHtmlFontSize = () => { const htmlDom = document.getElementsByTagName(’html’)[0]; let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth; if (htmlWidth >= 750) { htmlWidth = 750; } if (htmlWidth <= 320) { htmlWidth = 320; } htmlDom.style.fontSize = `${htmlWidth / 7.5}px`;};window.onresize = setHtmlFontSize;setHtmlFontSize();
注: 這里設(shè)置的比例是 100px = 1rem,例如:元素寬度為 100px 時(shí),可以直接寫(xiě)成 1rem
方法二:使用 lib-flexible 和 px2rem-loader 自動(dòng)轉(zhuǎn)換
1、安裝插件
npm install lib-flexible --save
npm install px2rem-loader --save-dev
2、配置插件
在入口文件 main.js 中引入 lib-flexible:
在 build/utils.js 文件中配置 px2rem-loader:
安裝并配置好 lib-flexible 和 px2rem 之后要重啟一下項(xiàng)目,才能自動(dòng)把 px 轉(zhuǎn)換成 rem。
內(nèi)聯(lián)的 px 樣式不能自動(dòng)轉(zhuǎn)換。
另外,px 寫(xiě)法上會(huì)有些不同,大家可以參考 px2rem 官方介紹,下面簡(jiǎn)單介紹一下。
1. 直接寫(xiě) px,編譯后會(huì)直接轉(zhuǎn)化成 rem;---- 【除下面兩種情況,其他長(zhǎng)度用這個(gè)】
2. 在 px 后面添加 /*no*/,不會(huì)轉(zhuǎn)化 px,會(huì)原樣輸出; ---- 【一般 border 用這個(gè)】
3. 在 px 后面添加 /*px*/,會(huì)根據(jù) dpr 的不同,生成三套代碼。---- 【一般 font-size 用這個(gè)】
示例代碼如下:
/* 編譯前 */.selector { width: 150px; height: 64px; /*px*/ font-size: 28px; /*px*/ border: 1px solid #ddd; /*no*/}/* 編譯后 */.selector { width: 2rem; border: 1px solid #ddd;}[data-dpr='1'] .selector { height: 32px; font-size: 14px;}[data-dpr='2'] .selector { height: 64px; font-size: 28px;}[data-dpr='3'] .selector { height: 96px; font-size: 42px;}
以上這篇vue項(xiàng)目中使用rem,在入口文件添加內(nèi)容操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
