美文网首页
前端js兼容显示器缩放问题

前端js兼容显示器缩放问题

作者: Frank_Fang | 来源:发表于2022-10-25 17:14 被阅读0次

    暂时还没找到兼容mac自带显示器和外接显示器的自适应缩放的解决方案。

    1. 在vue项目<utils>目录里加一个<devicePixelRatio.js>文件
    /**
     * @description 校正windows页面在系统进行缩放后导致页面被放大的问题,通常放大比例是125%、150%
     * **/
    
    class DevicePixelRatio {
      // 获取系统类型
      _getSystem () {
        // const flag = false
        var agent = navigator.userAgent.toLowerCase()
        if (agent.indexOf('windows') >= 0) {
        return true
        } else {
          return false
        }
      }
    
      // 获取页面缩放比例
      _addHandler (element, type, handler) {
        if (element.addEventListener) {
          element.addEventListener(type, handler, false)
        } else if (element.attachEvent) {
          element.attachEvent('on' + type, handler)
        } else {
          element['on' + type] = handler
        }
      }
    
      // 校正浏览器缩放比例
      _correct () {
        // 页面devicePixelRatio(设备像素比例)变化后,计算页面body标签zoom修改其大小,来抵消devicePixelRatio带来的变化。
        if (document.getElementsByTagName('body') && document.getElementsByTagName('body').length) {
          // 将当前视图缩放百分比作为变量存入body中
          document.getElementsByTagName('body')[0].style.zoom = 1 / window.devicePixelRatio
          document.getElementsByTagName('body')[0].style.setProperty('--c100vh', window.devicePixelRatio * 100 + 'vh')
        }
      }
    
      // 监听页面缩放
      _watch () {
        const t = this
        t._addHandler(window, 'resize', function () { // 注意这个方法是解决全局有两个window.resize
          // 重新校正
          t._correct()
        })
      }
    
      // 初始化页面比例
      init () {
        const t = this
        if (t._getSystem()) { // 判断设备,目前只在windows系统下校正浏览器缩放比例
          // 初始化页面校正浏览器缩放比例
          t._correct()
          // 开启监听页面缩放
          t._watch()
        }
      }
    }
    export default DevicePixelRatio
    
    1. 在<App.vue>里引入
    import DevicePixelRatio from '@/utils/devicePixelRatio.js'
    

    3.缩放后,100vh这种样式会有问题,在<App.vue>里加上修复代码:

      updated () {
        // 兼容屏幕缩放
        this.$nextTick(() => {
          new DevicePixelRatio().init()
        })
      }
    

    4.页面中使用100vh时,略作调整

    .main {
      height: calc(var(--c100vh) - 30px);
    }
    

    相关文章

      网友评论

          本文标题:前端js兼容显示器缩放问题

          本文链接:https://www.haomeiwen.com/subject/ndhozrtx.html