注:此方案针对于项目是1920*1080的UI的缩放
1、 JS文件-detectZoom
在项目src下的util文件夹下写一个JS文件
获取Windows|其他系统的缩放比例,一般笔记本是150%,显示器是100%。
export const detectZoom = () => {
let ratio = 1;
const screen = window.screen;
const ua = navigator.userAgent.toLowerCase();
if (window.devicePixelRatio !== undefined) {
ratio = window.devicePixelRatio;
} else if (ua.indexOf('msie') !== -1 && screen.deviceXDPI && screen.logicalXDPI) {
ratio = screen.deviceXDPI / screen.logicalXDPI;
} else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
ratio = window.outerWidth / window.innerWidth;
}
return Math.round(ratio * 100);
};
2、Vue项目的入口文件main.js中引入detectZoom.js
import {detectZoom} from "@/utils/detectZoom";
3.1、接着在main.js中定义方法来调整页面缩放
注:由于项目所需,我们这里判断了手机设备,只针对手机设备进行了页面缩放,如果手机电脑都需要缩放,使用3.2的代码
const applyResponsiveScaling = () => {
// 如果是手机
if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
const zoomLevel = detectZoom();
const screenWidth = window.screen.width * window.devicePixelRatio;
const baseWidth = 1920;
let zoomFactor;
let widthFactor;
if (screenWidth !== baseWidth) {
zoomFactor = screenWidth / baseWidth;
widthFactor = baseWidth / screenWidth;
} else {
zoomFactor = 1;
widthFactor = 1;
}
// 检测是否支持 zoom 属性
const supportsZoom = 'zoom' in document.body.style;
if (supportsZoom) {
document.body.style.zoom = (100 / zoomLevel) * zoomFactor;
} else {
// 对于不支持 zoom 的浏览器,如 Firefox,使用 transform: scale
document.body.style.transform = `scale(${(100 / zoomLevel) * zoomFactor})`;
document.body.style.transformOrigin = 'top left';
document.body.style.overflow = 'hidden'; // 隐藏滚动条
}
document.body.style.width = (zoomLevel * widthFactor) + "vw";
document.body.style.height = (zoomLevel * widthFactor) + "vh";
} else {
document.body.style.zoom = 1;
document.body.style.width = "100vw";
document.body.style.height = "100vh";
}
};
3.2、接着在main.js中定义方法来调整页面缩放
注:此代码针对所有设备都进行缩放
const applyResponsiveScaling = () => {
const zoomLevel = detectZoom();
const screenWidth = window.screen.width * window.devicePixelRatio;
const baseWidth = 1920;
let zoomFactor;
let widthFactor;
if (screenWidth !== baseWidth) {
zoomFactor = screenWidth / baseWidth;
widthFactor = baseWidth / screenWidth;
} else {
zoomFactor = 1;
widthFactor = 1;
}
// 检测是否支持 zoom 属性
const supportsZoom = 'zoom' in document.body.style;
if (supportsZoom) {
document.body.style.zoom = (100 / zoomLevel) * zoomFactor;
} else {
// 对于不支持 zoom 的浏览器,如 Firefox,使用 transform: scale
document.body.style.transform = `scale(${(100 / zoomLevel) * zoomFactor})`;
document.body.style.transformOrigin = 'top left';
document.body.style.overflow = 'hidden'; // 隐藏滚动条
}
document.body.style.width = (zoomLevel * widthFactor) + "vw";
document.body.style.height = (zoomLevel * widthFactor) + "vh";
};
4、应用于项目中
// 应用缩放调整
applyResponsiveScaling();
// 当窗口大小改变时重新应用
window.addEventListener('resize', applyResponsiveScaling);