vue3兼容超宽屏、超窄屏、4K屏幕等等

vue3兼容超宽屏、超窄屏、4K屏幕等等

在你的项目src下创建一个hooks文件夹 在里面创建一个 UserScalePage.ts文件
在里面写上

import { onMounted, onUnmounted } from "vue";
import _ from "lodash";
export default function UserScalePage(opstion: any) {
  const resizeFunc = _.throttle(function () {
    // 当页面发生改变的时候我们需要重新调用该函数重新计算当前需要的scale
    triggerScale(); // 动画缩放网页
  }, 100);
  function triggerScale() {
    // 1.设计稿的尺寸
    let targetX = opstion.targetX || 1920;
    let targetY = opstion.targetY || 1080;
    // 1.设计稿的比例
    let targetRatio = opstion.targetRatio || 16 / 9;

    // 第一步获取到当前设备的浏览器宽度
    // 如果window没有我们就去拿body的
    let currentX =
      document.documentElement.clientWidth || document.body.clientWidth;
    let currentY =
      document.documentElement.clientHeight || document.body.clientHeight;


    // 计算当前需要的缩放值
    let scaleRatioc = currentX / targetX; //默认情况下我们需要缩放的比率
    let currentRatio = currentX / currentY; //宽高的比率
    // 如果我们当前的比值大于我们的设计稿比值说明我们当前的屏幕比较的宽或者比较的高
    if (currentRatio > targetRatio) {
      scaleRatioc = currentY / targetY; //根据情况不同我们进行选择按照宽度或者高度进行适配
      document.body.style = `width:${targetX}px; height:${targetY}px;transform: scale(${scaleRatioc}) translateX(-50%); left: 50%`;
    } else {
      // 如果比值一样我们就直接缩放
      document.body.style = `width:${targetX}px; height:${targetY}px; transform: scale(${scaleRatioc})`;
    }
  }
  onMounted(() => {
    // console.log
    // 添加
    triggerScale();
    window.addEventListener("resize", resizeFunc);
  });
  onUnmounted(() => {
    // 释放
    window.removeEventListener("resize", resizeFunc);
  });
}

在你的app.vue中引入配置一下

<script setup lang="ts">
import { RouterView } from 'vue-router'
import UserScalePage from "./Hooks/UserScalePage";
let opstion = {
  targetX: 1920,
  targetY: 1080,
  targetRatio: 16 / 9,
};
UserScalePage(opstion);
</script>

<template>
  <RouterView />
</template>

<style scoped></style>

最后一步在你的base.css也就是公共样式表中对body进行样式重置

body {
  position: relative;
  width: 1920px;
  height: 1080px;
  box-sizing: border-box;
  /* border: 5px solid red; */
  transform-origin: left top;
}
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值