提要:
主要是针对页面宽高进行监听,检测最短边,并以最短边去适配16:9比例的页面元素。通常用于pc需要适配大屏和一些后台管理方面的项目。
vue2写法
<template>
<div class="container">
<div class="content" :style="getAspectRatioStyle">
<!-- 数据展示内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
contentWidth: 0,
contentHeight: 0
};
},
mounted() {
this.calculateAspectRatio();
window.addEventListener('resize', this.calculateAspectRatio);
},
beforeUnmount() {
window.removeEventListener('resize', this.calculateAspectRatio);
},
computed: {
getAspectRatioStyle() {
return {
width: `${this.contentWidth}px`,
height: `${this.contentHeight}px`,
margin: 'auto',
background: 'white'
};
}
},
methods: {
calculateAspectRatio() {
const container = document.querySelector('.container');
const containerWidth = container.offsetWidth;
const containerHeight = container.offsetHeight;
const aspectRatio = 16 / 9; // 16:9 比例
const containerAspectRatio = containerWidth / containerHeight;
if (containerAspectRatio > aspectRatio) {
// 以高度为基准,按比例计算宽度
this.contentHeight = containerHeight;
this.contentWidth = Math.floor(containerHeight * aspectRatio);
} else {
// 以宽度为基准,按比例计算高度
this.contentWidth = containerWidth;
this.contentHeight = Math.floor(containerWidth / aspectRatio);
}
}
}
};
</script>
<style>
.container {
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.content {
/* 根据计算得到的宽高样式设置 */
}
</style>
vue3写法
<template>
<div class="container">
<div class="content" :style="getAspectRatioStyle">
<!-- 数据展示内容 -->
</div>
</div>
</template>
<script>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
export default {
setup() {
const contentWidth = ref(0);
const contentHeight = ref(0);
const calculateAspectRatio = () => {
const container = document.querySelector('.container');
const containerWidth = container.offsetWidth;
const containerHeight = container.offsetHeight;
const aspectRatio = 16 / 9; // 16:9 比例
const containerAspectRatio = containerWidth / containerHeight;
if (containerAspectRatio > aspectRatio) {
// 以高度为基准,按比例计算宽度
contentHeight.value = containerHeight;
contentWidth.value = Math.floor(containerHeight * aspectRatio);
} else {
// 以宽度为基准,按比例计算高度
contentWidth.value = containerWidth;
contentHeight.value = Math.floor(containerWidth / aspectRatio);
}
};
onMounted(() => {
calculateAspectRatio();
window.addEventListener('resize', calculateAspectRatio);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', calculateAspectRatio);
});
const getAspectRatioStyle = computed(() => ({
width: `${contentWidth.value}px`,
height: `${contentHeight.value}px`,
margin: 'auto',
background: 'white'
}));
return {
getAspectRatioStyle
};
}
};
</script>
<style>
.container {
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.content {
/* 根据计算得到的宽高样式设置 */
}
</style>