数据大屏自适应方案

该博客介绍了一种新的屏幕适配方法,通过设置元素的scale属性来实现不同尺寸屏幕的适配,避免了使用rem和处理单位不一致的问题。在Vue2环境中,作者提供了具体的实现代码,通过计算屏幕宽高比与设计稿比例,调整盒子的scale值,确保内容在大屏设备上正确显示。这种方法允许开发者自由使用%和px单位,简化了前端开发中的适配流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用scale方式进行屏幕缩放实现适配大屏。无需特定编写rem,也不用考虑单位不一致导致的适配无效(%px随便用)。

原理:当我屏幕大小与设计稿大小不符的时候,计算缩放的比例,从而设置盒子的scale属性。

实例:Vue2用户可直接复制代码看看。react或angular用户参考示例琢磨一下

<template>
  <div class="box">
    <div class="screen" id="screen">
      <div class="contain-box">
        <div>
          侧边栏
        </div>
        <div>
          <header>这是头部</header>
          <section>这是身体</section>
          <footer>这是脚</footer>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  mounted() {
    this.handlerScale()
    window.onresize = () => this.handlerScale();
  },
  methods: {
    handlerScale(){
      let designWidth = 1920;   //设计图的宽度
      let designHeight = 620;   //设计图的高度
      const scale = document.documentElement.clientWidth / document.documentElement.clientHeight < designWidth / designHeight 
      ? (document.documentElement.clientWidth / designWidth) 
      : (document.documentElement.clientHeight / designHeight)
      document.getElementById('screen').style.transform = `scale(${scale}) translate(-50%)`

    }
  },  
  destroyed() {
    window.onresize = null;
  },
}
</script>

<style lang="less" scoped>
.box{
  width: 100%;
  height: 100%;
  .screen{
    width: 1920px;
    height: 100px;
    transform-origin: 0 0;
    position: absolute;
    left: 50%;
  }
  .contain-box{
    display: flex;
    >div:first-of-type{
      width: 200px;
      background-color: purple;
    }
    >div:last-of-type{
      flex: 1;
    }
  }
}
header{
  width: 100%;
  background-color: pink;
}
section{
  width: 100%;
  background-color: greenyellow;
}
footer{
  width: 100%;
  background-color: red;
}
</style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值