大屏适配方案

        现在大屏适配插件有很多PostCss,vue2-scale-box等。大多数都是基于rem方案和scale方案,今天来做一个总结。

1.rem方案

思路:设置 rem 的基准值 ,动态的计算html根元素的font-size

缺点:无法适配echarts图表字体需要单独做处理

2.translate方案,推荐

思路:基于css3属性transform进行实现,根据设计稿的宽高比,对最外层元素进行等比例缩小或放大,里面元素也跟随变化

缺点:一些屏幕宽高比和设计稿的宽高比不一致时会出现俩边留白

// 配置项
const init = {
  DOM: '#app', // dom元素
  baseWidth: 1920, //设计稿尺寸(px)
  baseHeight: 1080, //设计稿尺寸(px)
  // 默认缩放值
  scale: {
    width: '1',
    height: '1',
  }
}

// * 定时函数
let drawTiming = null
const {DOM, baseWidth, baseHeight, scale} = init

function calcRate () {
  const appRef = document.querySelector(DOM)
  // * 需保持的比例(默认1.77778)
  const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))
  if (!appRef) return 
  // 当前宽高比
  const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
  if (appRef) {
    if (currentRate > baseProportion) {
      // 表示更宽
      scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
      scale.height = (window.innerHeight / baseHeight).toFixed(5)
      appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
    } else {
      // 表示更高
      scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5)
      scale.width = (window.innerWidth / baseWidth).toFixed(5)
      appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
    }
  }
}

function resize () {
  clearTimeout(drawTiming)
  drawTiming = setTimeout(() => {
    calcRate()
  }, 200)
}

// 开启计算
export function startResize(){
  calcRate()
  window.addEventListener('resize', resize)
}

// 移除监听
export function removeResize(){
  window.removeEventListener('resize', resize)
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值