解决手机系统设置字体大小后,qq内置浏览器rem排版错乱问题


我们移动端项目用postcss-pxtorem插件来自适应rem

先要在计算根节点的字体

    const baseSize = 32;

    // 设置 rem 函数
    function setRem() {
      // 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。
      const scale = document.documentElement.clientWidth / 750;
      // 设置页面根节点字体大小
      document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
    }

    // 初始化
    setRem()
    // 改变窗口大小时重新设置 rem
    window.onresize = function () {
      setRem()
    };    

在qq内置浏览器中我发现添加的字体大小会随着系统设置的字体大小倍数走

最后找到window.getComputedStyle()方法能查询到放大后的字体大小,我们可以根据放大倍数来再次设置字体大小

最终修改完成

    // 基准大小
    const baseSize = 32;

    // 设置 rem 函数
    function setRem() {
      // 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。
      const scale = document.documentElement.clientWidth / 750;
      // 设置页面根节点字体大小
      let fontSize = baseSize * Math.min(scale, 2)
      document.documentElement.style.fontSize = fontSize + 'px'
      // 解决手机系统设置字体大小后,qq内置浏览器rem排版错乱问题
      // getComputedStyle能获取被系统放大后的字体
      let computedFontSize = window.getComputedStyle(document.getElementsByTagName("html")[0])['font-size'].replace(/px/gi, '')
      let multiple = fontSize / computedFontSize
      document.documentElement.style.fontSize = (fontSize * multiple) + 'px'
    }
    // 初始化
    setRem()
    // 改变窗口大小时重新设置 rem
    window.onresize = function () {
      setRem()
    };

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM