vue大屏适配通用容器方案

scaleBox.vue源码

<template>
  <div id="screen"
       :style="{
      width: `${style.width}px`,
      height: `${style.height}px`,
      transform: `${style.transform}`
    }">
    <slot />
  </div>
</template>
 
<script>
export default {
  props: {},
  data() {
    return {
      style: {
        width: '1920',
        height: '1080',
        transform: 'scaleY(1) scaleX(1) translate(-50%, -50%)',
      },
    }
  },
  methods: {
    getScale() {
      const w = window.innerWidth / this.style.width
      const h = window.innerHeight / this.style.height
      return { x: w, y: h }
    },
    setScale() {
      const scale = this.getScale()
      this.style.transform =
        'scaleY(' + scale.y + ') scaleX(' + scale.x + ') translate(-50%, -50%)'
    },
  },
  mounted() {
    const that = this
    that.setScale()
    /* 窗口改变事件 */
    window.addEventListener('resize', function () {
      that.setScale()
    })
  },
}
</script>
 
<style lang="scss">
#screen {
  z-index: 100;
  transform-origin: 0 0;
  position: fixed;
  left: 50%;
  top: 50%;
  transition: 0.3s;
}
</style>

基本实现布局效果 会根据视窗的变化调整大屏比例,容器内部编写直接按照宽1920px,高1080px单位为px的排版布局编写即可,其他的就交给上述代码即可,示例:

<template>
  <scale-box>
    <div class="main-wrapper">
      <div class="box1"></div>
      <div class="box2"></div>
    </div>
  </scale-box>
</template>

<script>
import scaleBox from './scaleBox.vue'
export default {
  components: {
    scaleBox,
  },
}
</script>

<style lang="scss" scoped>
.box1 {
  width: 1000px;
  height: 200px;
  background-color: orange;
}
.box2 {
  width: 920px;
  height: 200px;
  background-color: green;
}
.main-wrapper {
  height: 100%;
  display: flex;
}
</style>

效果图:
在这里插入图片描述
缩放后效果:
在这里插入图片描述
无论页面如何缩放,都会因为css3的transform属性实现等比例缩放

vue3写法:

<template>
  <div id="screen"
       :style="{
      width: `${style.width}px`,
      height: `${style.height}px`,
      transform: `${style.transform}`
    }">
    <slot />
  </div>
</template>

<script setup>
const style = ref({
  width: '1920',
  height: '1080',
  transform: 'scaleY(1) scaleX(1) translate(-50%, -50%)',
})

function getScale() {
  const w = window.innerWidth / style.value.width
  const h = window.innerHeight / style.value.height
  return { x: w, y: h }
}
function setScale() {
  const scale = getScale()
  style.value.transform =
    'scaleY(' + scale.y + ') scaleX(' + scale.x + ') translate(-50%, -50%)'
}
setScale()
/* 窗口改变事件 */
window.addEventListener('resize', function () {
  setScale()
})
</script>

<style lang="scss" scoped>
#screen {
  z-index: 100;
  transform-origin: 0 0;
  position: fixed;
  left: 50%;
  top: 50%;
  transition: 0.3s;
}
</style>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值