在原文的基础上改进了 https://www.jianshu.com/p/dd0c1fd838c2
子组件
<script>
export default {
props: {
width: number,
height: number,
minWidth: number,
},
data() {
return {
scale: 0,
realHeight: 0,
}
},
mounted() {
this.setScale()
window.addEventListener('resize', this.debounce(this.setScale))
},
methods: {
getScale() {
const wh = window.innerHeight / this.height
const ww = Math.max(this.minWidth, window.innerWidth) / this.width
this.realHeight = `${this.height * ww}px`
return ww
},
setScale() {
// 获取到缩放比例,设置它
this.scale = this.getScale()
if (this.$refs.ScaleBox)
this.$refs.ScaleBox.style.setProperty('--scale', this.scale)
},
debounce(fn, delay) {
const delays = delay || 100
let timer
return function () {
const that = this
const args = arguments
if (timer)
clearTimeout(timer)
timer = setTimeout(() => {
timer = null
fn.apply(that, args)
}, delays)
}
},
},
}
</script>
<template>
<div
style="width:100%;height:659px;overflow: hidden;" :style="{
height: realHeight,
}"
>
<div
ref="ScaleBox" class="ScaleBox" :style="{
width: `${width}px`,
height: `${height}px`,
}"
>
<slot />
</div>
</div>
</template>
<style>
#ScaleBox {
--scale: 1;
}
.ScaleBox {
transform: scale(var(--scale));
transform-origin: 0 0;
z-index: 999;
}
</style>
使用
<div style="min-width:1200px;overflow: auto;">
- -
<ScaleBox :height="659" :width="1920" :min-width="1200">
<div style="width:1920px">
<img src="/image/about/about3.png" alt="">
</div>
</ScaleBox>
- -
</div>
效果