在使用vue-cli搭建好项目框架后,在目录结构的index.html文件中添加一段js代码:
<script>
window.onload = function () {
var setRem = function () {
// UI设计稿的宽度
var uiWidth = 1200;
// 移动端屏幕宽度
var winWidth = document.documentElement.clientWidth;
// 比率
var rate = winWidth / uiWidth;
// 设置html元素的字体大小
document.documentElement.style.fontSize = rate * 20 + "px"
};
setRem();
window.onresize = function () {
setRem();
}
}
</script>
然后在写css就可以将px单位换成rem.
这里设置的比例是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 开发 H5 项目时,需要进行 rem 适配,下面提供两种常用的方法(以 750 设计稿为例),希望对大家有所帮助。
方法一:在 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();
注: 这里设置的比例是 100px = 1rem,例如:元素宽度为 100px 时,可以直接写成 1rem
方法二:使用 lib-flexible 和 px2rem-loader 自动转换
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 转换成 rem。
内联的 px 样式不能自动转换。
另外,px 写法上会有些不同,大家可以参考 px2rem 官方介绍,下面简单介绍一下。
1. 直接写 px,编译后会直接转化成 rem;—- 【除下面两种情况,其他长度用这个】
2. 在 px 后面添加 /*no*/,不会转化 px,会原样输出; —- 【一般 border 用这个】
3. 在 px 后面添加 /*px*/,会根据 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,在入口文件添加内容操作就是小编分享给大家的全部内容了。
- vue3.2+ts实现在方法中可调用的拟态框弹窗(类el-MessageBox)
- 可能是全网vue v-model最详细讲解教程
- Vue3中echarts无法缩放的问题及解决方案
- Vue $nextTick 为什么能获取到最新Dom源码解析
- Vue生命周期实例分析总结
- Vue实现简单基础的图片裁剪功能
- vue.config.js 的完整配置(超详细)
- vue原生input输入框原理剖析
版权:版权申明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 70068002@qq.com 举报,一经查实,本站将立刻删除。
转载请注明出处:https://www.stntk.com/2500.html
还没有评论呢,快来抢沙发~