vue3大屏适配之常见方案

1.rem 单位 + 动态设置 html 的 font-size(不推荐)

如将设计稿的宽(1920)平均分成 24 等份, 每一份为 80px。

动态设置 html 的 font-size可以使用媒体查询或者js来动态改变body的fontsize大小,媒体查询太麻烦,以下是通过js代码动态改变fontsize大小。

<template>
  <div class="factory">
    哈哈哈哈
    <img src="@/assets/screen/arrow.png" alt="">
  </div>
</template>

<script setup>
import { nextTick } from 'vue';
onMounted(() => {
  nextTick(() => {
    changesizeFn()
  })
  window.addEventListener('resize', changesizeFn)
})

const changesizeFn = () => {
  let targetX = 1920
  let x = document.documentElement.clientWidth
  //获取body,并改变body的fontsize大小
  let body = document.documentElement
  body.style.fontSize = `${(x / targetX) * 24}px`
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', changesizeFn)
})
</script>

<style lang="scss" scoped>
.factory {
  width: 24rem;
  height: 13.5rem;
  font-size: 0.225rem;

  img {
    height: .525rem;
  }
}
</style>

缺点:一些第三方库的字体等默认的都是px单位,比如:element、echarts,因此通常需要层叠第三方库的样式,比如有的图表需要单独适配字体。

2.vw/vh

使用vw、vh适配的优点是可以根据屏幕大小自动调整元素大小,使得页面在不同设备上都能够呈现出较好的效果。直接是响应式的,不需要resize事件,

<template>
  <div class="factory">
    哈哈哈哈
    <img src="@/assets/screen/arrow.png" alt="">
  </div>
</template>

<script setup>

</script>

<style lang="scss" scoped>
.factory {
  width: 100vw;
  height: 56.25vw;
  font-size: 1vw;

  img {
    height: 3vw;
  }
}
</style>

缺点:一些第三方库的字体等默认的都是px单位,比如:element、echarts,因此通常需要层叠第三方库的样式,比如有的图表需要单独适配字体。像素较小的情况下不精准。

3.scale(推荐)

直接根据宽度的比率进行缩放。(宽度比率=网页当前宽 / 设计稿宽)

<template>
  <div class="factory">
 </div>
</template>

<script setup>
import { nextTick } from 'vue'
onMounted(() => {
   nextTick(() => {
     changeScale()
   })
    window.addEventListener('resize', changeScale)
}
const changeScale = () => {
  let targetX = 1920
  let x = document.documentElement.clientWidth
  let scaleX = x / targetX
  //动态缩放
  document.querySelector('.factory').setAttribute('style', `transform:scale(${scaleX}`)
}
onBeforeUnmount(() => {
  window.removeEventListener('resize', changeScale)
})
</script>

<style lang="scss" scoped>
  width: 1920px;
  height: 1080px;
  transform-origin: left top; //此处必须加上这个属性,让屏幕一直处于左上角
</style>

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值