前端实现大屏缩放自适应屏幕
思路:
- 页面初始化获取屏幕的原始比例
- 将自适应元素的scale变量设置为当前比例
- 监听浏览器窗口大小,获取新的比例值重新给元素scale赋值
vue2—封装的代码组件
<template><divclass="ScaleBox"ref="ScaleBox":style="{width: width + 'px',height: height + 'px'}"><slot></slot></div>
</template>
<script>
export default {props: {// 标准内容宽度uiContentWidth: {type: Number,default: 1920},// 标准内容高度uiContentHeight: {type: Number,default: 0},// 其他内容的宽度otherWidth: {type: Number,default: 300 //左侧菜单栏默认宽度,如果没有则忽略}},data () {return {width: 1920, // 初始宽height: 1080, // 初始高zoom: 1 // 计算要缩放的 宽度比(浏览器可视宽度与设计稿的宽度比)}},mounted () {this.setScale()window.addEventListener('resize', this.debounce(this.setScale, 100))},beforeDestroy () {window.removeEventListener('resize', this.debounce)},methods: {getScale () {// 当前屏幕下需要适配内容的宽度 = 屏幕的宽度 - 其他不需要适配的内容的宽度const innerWidth = window.innerWidth - this.otherWidth// 内容元素需要改变的大小比例 = 当前屏幕尺寸需要变化到标准尺寸的比例 / 标准比例this.zoom = Number(innerWidth / this.uiContentWidth)// 设置缩放后的宽高this.width = innerWidth},setScale () {this.getScale()if (this.$refs.ScaleBox) {this.$refs.ScaleBox.style.setProperty('--scaleww', this.zoom)this.$refs.ScaleBox.style.setProperty('--scalewh', this.zoom)}},debounce (fn, delay) {const delays = delay || 500let timerreturn function () {const th = thisconst args = argumentsif (timer) {clearTimeout(timer)}timer = setTimeout(function () {timer = nullfn.apply(th, args)}, delays)}}}
}
</script><style lang="scss">
body {&::-webkit-scrollbar {display: none;}
}
#ScaleBox {--scaleww: 1;--scalewh: 1;
}
.ScaleBox {transform: scale(var(--scaleww), var(--scalewh));display: flex;flex-direction: column;transform-origin: 0 0;transition: 0.3s;z-index: 3;
}
.no-zoom {transform: scale(var(1 / --scaleww), var(1 / --scalewh));
}
</style>