场景:
平时做大屏态势图或者大屏的满是图表的界面的时候,最头疼的就是如果兼容各种分辨率的屏幕,做到等比例缩放显示,保持内容排版和相对大小、位置等。
那么看下面这个,简直就是宝藏做法。(但是也存在一定的不足)
效果图:
注意看浏览器比例
实现:
容器:
<template>
<el-container class="main-container" style="height: 100% ;overflow: hidden">
<div class="bigscreen-body" ref="appRef">
<el-container style="height: calc(100% - 100px);width:100%;">
<div class="mianPage">
<div class="mianPage-main mianPage-col" >
<!-- 主体部分 -->
</div>
</el-container>
</div>
</el-container>
</template>
<script>
import scaleMixin from "./utils/scaleMixin";
export default {
mixins: [ scaleMixin],
data() {
return {}
},
beforeCreate(){
},
methods:{
}
}
</script>
<style lang="scss" scoped>
...略
</style>
重点是这个mixin
他绑定了元素,从而实现等比例缩放
但是这种做法也有缺点。
就是你需要默认定死一个宽高,不能做到完美的盛满屏幕,或许上下、或许左右会出现空白的情况
scaleMixin.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 appRef = this.$refs["appRef"]
if (!appRef) return
// 当前宽高比
const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
if (appRef) {
if (currentRate > baseProportion) {
// 表示更宽
scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
scale.height = (window.innerHeight / baseHeight).toFixed(5)
appRef.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)
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
}
localStorage.setItem('windowScale',scale.width)
}
},
resize () {
clearTimeout(this.drawTiming)
this.drawTiming = setTimeout(() => {
this.calcRate()
}, 200)
}
},
}