使用要求:指定容器的 id 为 bigScreenContainer
一、效果图
不管你的屏幕多大都会根据设计稿 1920*1080 进行缩放
图一:缩小的效果
图二:放大的效果
二、使用方式
<template>
<div id="bigScreenContainer" ref="bigScreenContainer">
// 内容
</div>
</template>
<script>
// import { bigScreenAdapterMixin } from "snows-utils";
import bigScreenAdapterMixin from "@/utils/bigAdapterMixin";
export default {
name:'',
mixins: [bigScreenDdapterMixin],
</script>
三、实现代码
/*
* @Description: ------------ fileDescription -----------
* @Author: snows_l snows_l@163.com
* @Date: 2023-11-16 09:35:24
* @LastEditors: snows_l snows_l@163.com
* @LastEditTime: 2023-11-16 10:47:15
* @FilePath: /source-snows-utils/utils/bigAdapterMixin.js
*/
// 屏幕适配 mixin 函数
// * 默认缩放值
const scale = {
width: '1',
height: '1'
};
// * 设计稿尺寸(px)
const baseWidth = 1920;
const baseHeight = 1080;
// * 需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));
export default {
data() {
return {
// * 定时函数
drawTiming: null
};
},
mounted() {
this.calcRate();
window.addEventListener('resize', this.resize);
},
beforeDestroy() {
window.removeEventListener('resize', this.resize);
},
methods: {
calcRate() {
const style = {
width: '1920px',
height: '1080px',
position: 'absolute',
top: '50%',
left: '50%',
transformOrigin: 'left top'
};
const bigScreenContainer = document.getElementById('bigScreenContainer');
if (!bigScreenContainer) return;
// 设置必要样式(上下左右居中)
bigScreenContainer.style.width = style.width;
bigScreenContainer.style.height = style.height;
bigScreenContainer.style.position = style.position;
bigScreenContainer.style.top = style.top;
bigScreenContainer.style.left = style.left;
bigScreenContainer.style.transformOrigin = style.transformOrigin;
// 当前宽高比
const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5));
if (bigScreenContainer) {
if (currentRate > baseProportion) {
// 表示更宽
scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5);
scale.height = (window.innerHeight / baseHeight).toFixed(5);
bigScreenContainer.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
} else {
// 表示更高
scale.height = (window.innerWidth / baseProportion / baseHeight).toFixed(5);
scale.width = (window.innerWidth / baseWidth).toFixed(5);
bigScreenContainer.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
}
}
},
resize() {
clearTimeout(this.drawTiming);
this.drawTiming = setTimeout(() => {
this.calcRate();
}, 200);
}
}
};
四:也可以直接安装 snows-utils 工具直接在里面引用
snows-utils 中包含了很多使用的方法
一些常用的工具函数(snows-utils),已发npm,会陆续更新-CSDN博客https://blog.csdn.net/snows_l/article/details/131384116?spm=1001.2014.3001.5501
<template>
<div id="bigScreenContainer" ref="bigScreenContainer">
// 内容
</div>
</template>
<script>
import { bigScreenAdapterMixin } from "snows-utils";
// import bigScreenAdapterMixin from "@/utils/bigadapterMixin";
export default {
name:'',
mixins: [bigScreenAdapterMixin],
</script>