方法一:插件适配,安装lodash
js
npm i lodash -S
在App.vue中给根节点挂载 ref=app
html
<template>
<div id="app" ref="app">
<router-view />
</div>
</template>
然后在mounted方法中执行,或者分装工具类引入调用也可,此处仅展示具体方法
js
<script>
import _ from "lodash";
export default {
name: "App",
mounted() {
this.$nextTick(() => {
const $app = this.$refs.app;
// 设置 屏幕 百分比 尺寸 适配
const standardScale = "100%" / "100%";
window.addEventListener(
"resize",
_.debounce(function () {
const docHeight = document.body.clientHeight;
const docWidth = document.body.clientWidth;
if (docWidth < 1680) {
const currentScale = docHeight / docWidth;
let [scale, translate] = [0, 0];
if (currentScale < standardScale) {
// 以高度计算
scale = docHeight / 1080;
const shouleWidth = 1920 * scale;
const offsetWidth = docWidth - shouleWidth;
translate =
offsetWidth > 0 ? `translate(${offsetWidth / 2}px, 0)` : "";
} else {
// 以宽度计算
scale = docWidth / 1920;
const shouleHeight = 1080 * scale;
const offsetHeight = docHeight - shouleHeight;
translate =
offsetHeight > 0 ? `translate(0, ${offsetHeight / 2}px)` : "";
}
console.log(translate);
$app.style.cssText = `
transform: scale(${scale}) ${translate};
transform-origin: top left;
min-width: 1920px;
min-height: 1080px;
`;
} else {
$app.style.cssText = "";
}
}),
300
);
if (document.createEvent) {
var event = document.createEvent("HTMLEvents");
event.initEvent("resize", true, true);
window.dispatchEvent(event);
} else if (document.createEventObject) {
window.fireEvent("onresize");
}
});
},
};
方法二:创建utils工具类
在utils下创建devicePixelRatio.js
js
class devicePixelRatio {
constructor() {
}
//获取系统类型
_getSystem() {
let flag = false;
var agent = navigator.userAgent.toLowerCase();
if(agent.indexOf("windows") >= 0) {
return true;
}
}
//获取页面缩放比例
_addHandler(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else if(element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
//校正浏览器缩放比例
_correct() {
let t = this;
//页面devicePixelRatio(设备像素比例)变化后,计算页面body标签zoom修改其大小,来抵消devicePixelRatio带来的变化。
document.getElementsByTagName('body')[0].style.zoom = 1 / window.devicePixelRatio;
}
//监听页面缩放
_watch() {
let t = this;
t._addHandler(window, 'resize', function() { //注意这个方法是解决全局有两个window.resize
//重新校正
t._correct()
})
}
//初始化页面比例
init() {
let t = this;
if(t._getSystem()) { //判断设备,目前只在windows系统下校正浏览器缩放比例
//初始化页面校正浏览器缩放比例
t._correct();
//开启监听页面缩放
t._watch();
}
}
}
export default devicePixelRatio;
在App.vue中调用
js
import DevicePixelRatio from '@/utils/DevicePixelRatio.js';
mounted() {
new DevicePixelRatio().init();
}