项目场景:
项目场景:根据UI图设计1920*1080 在台式机上开发显示正常,项目上线后在不同分辨率下样式显示错乱问题
解决方案:
在vue项中,使用钩子函数mounted,:
mounted() {
this.listenResize();
// window.addEventListener("wheel", this.disableScroll, { passive: false });
},
在methods中调用方法,其中的if判断是根据调试而来,具体可根据自己调试修改:
initScale() {
let containerWidth = window.innerWidth;
let containerHeight = window.innerHeight;
//console.log(containerHeight, containerWidth);
containerWidth = isNaN(containerWidth) ? 0 : containerWidth;
containerHeight = isNaN(containerHeight) ? 0 : containerHeight;
let defaultHeight = 1080;
let defaultWidth = 1920;
// sacle 缩放比例。
let scalex = containerWidth / defaultWidth;
let scaley = containerHeight / defaultHeight;
this.scaleX = scalex;
this.scaleY = scaley;
// console.log("111", this.scaleX)
// console.log("222", this.scaleY)
if (this.scaleX > 1) {
this.scaleX = 1
}
if (this.scaleY > 0.862) {
this.scaleY = 0.862
}
let marginWidth = (defaultWidth * (1 - this.scaleX)) / 2;
let marginHeight = (defaultHeight * (1 - this.scaleY)) / 2;
this.marginWidth = marginWidth;
this.marginHeight = marginHeight;
},
listenResize() {
this.initScale();
window.addEventListener("resize", () => {
this.initScale();
});
}
使用computed计算当前屏幕分辨率变化,:
computed: {
transformStyle: function () {
// console.log(this.scaleX, this.scaleY);
// console.log(this.marginHeight, this.marginWidth);
return {
transform: `scale(${this.scaleX}, ${this.scaleY})`,
margin: `-${this.marginHeight}px -${this.marginWidth}px`,
};
},
routes() {
return JSON.parse(sessionStorage.getItem("role"));
},
},
最后写样式:
transformStyle: function () {
this.$store.commit("scale/UPDATE_SCALE", {
x: this.scaleX,
y: this.scaleY,
});
return {
transform: `scale(${this.scaleX}, ${this.scaleY})`,
margin: `-${this.marginHeight}px -${this.marginWidth}px`,
};
},
在页面根元素动态绑定此样式,我这里是相当于在后台管理系统中的layout加上此样式:
<div class="login" :style="transformStyle">