屏幕100%/125%/150%缩放时的解决办法,以及修改之后定高的处理

2,492 阅读2分钟

这几天写项目时都是在100%缩放,1920*1080的情况下写的,然后自己看着当然没问题,但是换到笔记本上(win10笔记本默认一般都是125%或者150%),就发现全乱套了.

一开始在想是不是自适应的问题,但是发现其实人家都是1920*1080,没错啊.后来百度查查,明白是缩放的问题,把代码cv一下,页面基本上就能按照缩放跑了,附上原文解决地址

blog.csdn.net/qq_43405603…

然后就发现其实虽然页面上大多数地方都正常了,但是部分地方设置了固定高度之后,还是会出现长了短了的情况,在100%缩放的时候的500px和150%缩放的时候展现的效果就差一些,有时候会破坏页面布局.

我先把我的解决办法说一下,写一个工具函数放在utils里,这个函数接收一个高度值,按照缩放的不同返回一个新的高度值.因为在缩放变化的时候,浏览器上面的书签/地址栏之类的那些东西也会发生大小变化,在100%的时候,页面高度是929px,在125%的时候,是892px,在150%的时候是854px,也就是每大25%,就会多占据37像素的高度.

getZoomHeight.js:

// 根据当前缩放大小返回对应的高度
export const getZoomHeight = (oldHeight) => {
  let ratio = 0,
    screen = window.screen,
    ua = navigator.userAgent.toLowerCase();
  console.log("screen", screen);
  console.log("ua", ua);
  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio;
    console.log("window.devicePixelRatio !== undefined", ratio);
  } else if (~ua.indexOf("msie")) {
    if (screen.deviceXDPI && screen.logicalXDPI) { 
      ratio = screen.deviceXDPI / screen.logicalXDPI;
    }
  } else if (
    window.outerWidth !== undefined &&
    window.innerWidth !== undefined
  ) {
    ratio = window.outerWidth / window.innerWidth;
  }
  if (ratio) {
    ratio = Math.round(ratio * 100);
  }
  console.log("final", ratio);
  // return ratio;
  let newHeight = 0;
  if (ratio == 100) {
    // 100%缩放
    newHeight = oldHeight;
  }
  if (ratio === 125) {
    // 125%缩放
    newHeight = oldHeight / 1.25 + 37;
  }
  if (ratio == 150) {
    // 150%缩放
    newHeight = oldHeight / 1.5 + 74;
  }
  return newHeight;
};

import { getZoomHeight } from "@/utils/getZoomHeight";

let height = getZoomHeight(实际上100%缩放时的高度)

这个height就是对应的高度了