应用场景:数据屏自动适配屏幕大小
原理:transform的属性scale将盒子整体等比放大缩小
废话不多说,直接上代码!
<template>
<div class="container">
<!-- 数据大屏展示内容区域 -->
<div class="screen" ref="screen">
</div>
</div>
</template>
<script setup lang='ts'>
import { ref,onMounted } from 'vue';
//获取数据大屏展示内容盒子的DOM元素
let screen = ref();
onMounted(() => {
screen.value.style.transform = `scale(${getScale()}) translate(-50%,-50%)`
});
//定义大屏缩放比例
function getScale(w = 1920, h = 1080) {
const ww = window.innerWidth / w;
const wh = window.innerHeight / h;
return ww < wh ? ww : wh;
}
//监听视口变化
window.onresize = () => {
screen.value.style.transform = `scale(${getScale()}) translate(-50%,-50%)`
}
</script>
<style scoped lang='less'>
.container {
width: 100vw;
height: 100vh;
background: url(./images/bg.png) no-repeat;
background-size: cover;
.screen {
position: fixed;
width: 1920px;
height: 1080px;
left: 50%;
top: 50%;
transform-origin: left top;
background-color: red;
}
}
</style>
getScale(w = 1920, h = 1080)的宽高为你要设计的数据大屏宽高,这时你就会发现页面就是响应式的了,一次性解决所有问题,减少vh,vw适配的计算烦劳。