在plugins新建rem.js(PC端)
// 隔离作用域,避免全局变量的污染
!(function () {
function setHtmlFontSize() {
var whdef = 100 / 1920; // 表示1920的设计图,使用100PX的默认值
var bodyWidth = document.documentElement.getBoundingClientRect().width; // 当前窗口的宽度
console.log(bodyWidth, '屏幕宽度');
var rem = bodyWidth * whdef; // 以默认比例值乘以当前窗口宽度,得到该宽度下的相应FONT-SIZE值
document.getElementsByTagName('html')[0].style.fontSize = rem + 'px'
}
setHtmlFontSize();
window.addEventListener("resize", function () {
setTimeout(function () {
setHtmlFontSize();
}, 100)
})
})();
在plugins新建rem.js(手机端)
// 隔离作用域,避免全局变量的污染
!(function () {
function setHtmlFontSize() {
var whdef = 100 / 750; // 表示750的设计图,使用100PX的默认值
var bodyWidth = document.documentElement.getBoundingClientRect().width; // 当前窗口的宽度
console.log(bodyWidth, '屏幕宽度');
var rem = bodyWidth * whdef; // 以默认比例值乘以当前窗口宽度,得到该宽度下的相应FONT-SIZE值
document.getElementsByTagName('html')[0].style.fontSize = rem + 'px'
}
setHtmlFontSize();
window.addEventListener("resize", function () {
// setTimeout 是为了解决在苹果手机上的闪屏情况
setTimeout(function () {
setHtmlFontSize();
}, 100)
})
})();
在nuxt.config.js中引入js
plugins: [
{
src: '@/plugins/rem',
ssr: false
},
],
页面使用(index.vue)
<!--html:-->
<div class="title">签到成功</div>
<!--普通css:-->
.title {
font-size: 16px;
font-family: PingFangSC-Medium, PingFang SC;
font-weight: bold;
color: #242e42;
margin-bottom: 10px;
}
<!--转换为rem的css写法(100px=1rem):-->
.title {
font-size: 0.16rem;//16px写成0.16rem是因为我们在main.js设置了1920的设计图,使用了100px的默认值,所以我们在转换的时候直接用设计图的px值除以100就是现在的rem值(例:16px/100=0.16rem)
font-family: PingFangSC-Medium, PingFang SC;
font-weight: bold;
color: #242e42;
margin-bottom: 0.1rem;
}