大屏屏幕自适应大小的JS写法

发布时间 2023-09-11 14:32:34作者: 洛晨随风

本项目用的是vue开发,首先需要定义一下根节点app节点的大小,这里用1920的默认宽度定义

    <style>
      #app {
        width: 1920px;
        margin: 0 auto;
        transform: scale(1);
        transform-origin: 0 0;
      }
    </style>

js部分通过缩放的写法去在每次页面变化的时候执行计算宽高

    // web定稿尺寸 19820*1080
const initPageW = 1920,
  initPageH = 1080

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func: any, wait?: any, immediate?: any) {
  let timeout: any, args: any, context: any, timestamp: any, result: any

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }
  return function (...args: any) {
    // @ts-ignore
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

// 根据窗口的广澳变动的比例进行缩放 设置动画原点
function animateResize() {
  var _jsc: any = document.getElementById('app'),
    _body: any = document.getElementById('content')

  let WH = window.innerHeight,
    WW = window.innerWidth,
    _jscH = _jsc.offsetHeight
  if (initPageW < WW) {
    //超过设计稿宽度后不进行缩放,居中显示
    _jsc.style.transform = 'scale(1)'
    _jsc.style.margin = '0 auto'
    if (_body) {
      _body.style.height = 'auto'
    }
  } else {
    // 缩放
    let minScale = Math.floor((WW / initPageW) * 10000) / 10000
    // 浏览器的滚滚动条宽度 17px
    // 内容区高度缩放后如果超过窗口高度,说明出现滚动条,可视区域宽度会缩小17px 重新计算缩放比,
    if (_jscH * minScale > WH) {
      minScale = Math.floor(((WW - 17) / initPageW) * 10000) / 10000
    }
    _jsc.style.transform = 'scale(' + minScale + ',' + minScale + ')'
    _jsc.style.margin = '0 0'
    if (_body) {
      _body.style.height = _jscH * minScale + 'px'
    }
  }
}
const _debounce = debounce(function () {
  animateResize()
}, 500)
window.onresize = _debounce as any

export { animateResize, _debounce }

最后在调用处引入即可

import { animateResize } from '~/utils/resize'

onMounted(() => {
  animateResize()
})

他会根据计算的属性最后生成类似如下的css样式:
transform: scale(0.9911, 0.9911)
从而达到自适应的效果