在使用rem时,先要和ui确定设计的尺寸大小,比如是设计图是按照1920设计的,现在我们只需定义document.documentElement.style.fontSize 就行,一般为了方便比例一般是1:100,即100px为1rem,具体配置如下
在vue里面
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>',
mounted () {
this.baseVal = 1920;
this.rem(1);
on(window, 'resize', this.resizeFn);
},
methods: {
rem (n) {
let r = document.documentElement.clientWidth;
this.clientWidth = r;
if (r < 1600) {
r = 1600;
}
if (r > this.baseVal) {
r = this.baseVal;
}
// 根元素=当前页面的实际宽度*100/设计图尺寸(前端页面标准尺寸)*参数
document.documentElement.style.fontSize = (r * 100 / (this.baseVal * n)) + 'px';
if (this.clientWidth > this.baseVal) {
document.body.style.zoom = this.clientWidth / this.baseVal;
// document.body.style.transformOrigin = 'left top';
// document.body.style.transform = `scale(${this.clientWidth / this.baseVal})`;
}
},
resizeFn () {
clearTimeout(this.remTimer);
this.remTimer = setTimeout(() => {
this.rem(1);
}, 300);
}
},
destroyed () {
off(window, 'resize', this.resizeFn);
}
});
这样我们的页面在1920上面,根元素就为100px,设计图上100px我们就可以直接用1rem来写样式,这里有两个临界值,在页面大于1920,就按照1920来计算,小于1600,就按照1600计算,同时加了resize事件,当进行缩放时,重新进行计算