移动端适配

移动端font-size的适配

前言

有的时候,我们在使用font-size和rem来给移动端做适配会遇到这样一个问题,在微信中设置字体的大小会影响到rem 的比例,年轻人把字体调小,老年人把字体调大,这样会让我们原本的适配失效,造成页面字体样式错位的问题,下面的代码便可以解决这样的问题。

思路

先动态获取到微信调整字体的比例的倒数 scale,然后对rem 的比例进行还原;

  1. 先创建一个width为1rem的盒子,并设置为不可见,然后通过获取他的offsetWidth得到它以px为单位的物理宽度instanceWidth(offsetWidth的单位是px),目的是为了计算当前的1rem等于多少px;
  2. 再获取当前根元素html的font-size值 ,即htmlFontSize(也是以px为单位的),正常情况下1rem = 16px,也就是htmlFontSize等于1rem,但是当被缩放或者放大后就不相等了,我们需要对htmlFontSize与instanceWidth相除 (scale = htmlFontSize / instanceWidth),获取到微信调整字体的比例的倒数scale;
  3. 为了使 rem 的比例还原,我们要将页面字体的font-size换算后的px的值与scale相乘,将字体大小还原回去。

代码

(function (win, doc) {
  //创建一个1rem的盒子
  function createScaleElement() {
    let scaleDom = document.createElement('div')
    
    scaleDom.style.cssText = 'width:1rem;height:0;overflow:hidden;position:absolute;z-index:-2;visibility:hidden;'
    document.body.appendChild(scaleDom)
    return scaleDom
  }
  
  if (!win.addEventListener) {
    return
  }

  let scaleDom = createScaleElement()

  function setFont() {
    let scale = toScale()
    let html = document.documentElement
    let k = 640
    
    html.style.fontSize = (html.clientWidth / k * 100)*scale + 'px'
  }

  function getOriginalHtmlFontSize() {
    let rootDom = document.querySelector('html')
    let fontSize = rootDom.style.fontSize || 16

    return fontSize
  }

  function toNum(fontSize) {
    
    if(typeof fontSize === 'string') {

      fontSize = fontSize.replace('px', '')
      return Number(fontSize)    
    }

    return fontSize
  }

  function toScale() {
    let htmlFontSize = getOriginalHtmlFontSize()
    let instanceWidth = scaleDom.offsetWidth
    let scale = 1

    if(window.getComputedStyle) {
      instanceWidth = window.getComputedStyle(scaleDom).width
    }

    htmlFontSize = toNum(htmlFontSize)
    instanceWidth = toNum(instanceWidth)

    if(
      (typeof htmlFontSize == 'number' && htmlFontSize != 0) && 
      (typeof instanceWidth == 'number' && instanceWidth != 0)
    ) {
        
      if(Math.abs(htmlFontSize-instanceWidth)<0.1) {
        return 1
      }

      scale = htmlFontSize/instanceWidth
    }

    return scale
  }

  setFont()
  setTimeout(function () {
    setFont()
  }, 300)

  doc.addEventListener('DOMContentLoaded', setFont, false)
  win.addEventListener('resize', setFont, false)
  win.addEventListener('load', setFont, false)
})(window, document)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值