vue項目中使用rem,在入口文件添加內(nèi)容操作
在使用vue-cli搭建好項目框架后,在目錄結(jié)構(gòu)的index.html文件中添加一段js代碼:
<script> window.onload = function () { var setRem = function () { // UI設(shè)計稿的寬度 var uiWidth = 1200; // 移動端屏幕寬度 var winWidth = document.documentElement.clientWidth; // 比率 var rate = winWidth / uiWidth; // 設(shè)置html元素的字體大小 document.documentElement.style.fontSize = rate * 20 + "px" }; setRem(); window.onresize = function () { setRem(); } } </script>
然后在寫css就可以將px單位換成rem.
這里設(shè)置的比例是20px=1rem,
例如:寬度為100px時,可以直接寫成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);
補充知識:vue 中使用 rem 布局的兩種方法
在使用 vue-cli 開發(fā) H5 項目時,需要進(jìn)行 rem 適配,下面提供兩種常用的方法(以 750 設(shè)計稿為例),希望對大家有所幫助。
方法一:在 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 時,可以直接寫成 1rem
方法二:使用 lib-flexible 和 px2rem-loader 自動轉(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 之后要重啟一下項目,才能自動把 px 轉(zhuǎn)換成 rem。
內(nèi)聯(lián)的 px 樣式不能自動轉(zhuǎn)換。
另外,px 寫法上會有些不同,大家可以參考 px2rem 官方介紹,下面簡單介紹一下。
1. 直接寫 px,編譯后會直接轉(zhuǎn)化成 rem;---- 【除下面兩種情況,其他長度用這個】
2. 在 px 后面添加 /*no*/,不會轉(zhuǎn)化 px,會原樣輸出; ---- 【一般 border 用這個】
3. 在 px 后面添加 /*px*/,會根據(jù) dpr 的不同,生成三套代碼。---- 【一般 font-size 用這個】
示例代碼如下:
/* 編譯前 */ .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項目中使用rem,在入口文件添加內(nèi)容操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue項目搭建以及全家桶的使用詳細(xì)教程(小結(jié))
這篇文章主要介紹了vue項目搭建以及全家桶的使用詳細(xì)教程(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12使用vue-cli導(dǎo)入Element UI組件的方法
這篇文章給大家介紹了使用vue-cli導(dǎo)入Element UI組件的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友一起看看吧2018-05-05vue中在vuex的actions中請求數(shù)據(jù)實例
今天小編就為大家分享一篇vue中在vuex的actions中請求數(shù)據(jù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11