移动端rem自适应-函数封装

56 阅读1分钟

定义

em: 相对于元素的父元素的font-size进行计算。 
rem: 相对于根元素html的font-size进行计算。

orientationchange事件:在设备的纵横方向改变时触发(存在兼容性)。符。 
resize事件:窗口大小改变时触发。

document.write(): 当前编辑位置为写入的内容的后一个字符。 
document.writeln():  添加一个换行符,当前编辑位置为写入的内容的后一行的起。

DOMContentLoaded事件:是在文档完全加载和解析之后触发。与window.onload事件非常相似,但是onload事件不但文档完全加载和解析完毕,相关资源都要加载完毕,比如图片和CSS文件等。

核心代码

<script>
     (function () {
          var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
          var recalc = function () {
            var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
            if (!clientWidth) return
            document.documentElement.style.fontSize = clientWidth / 30 + 'px';  //根据你所在公司的具体情况灵活设置
            document.documentElement.style.visibility = 'visible';
          }
          if (!document.documentElement.addEventListener) {
            return;
          }
          window.addEventListener(resizeEvt, recalc, false);
          document.addEventListener('DOMContentLoaded', recalc, false);
    })();
    
    
    //按需引入vConsole
       // var ua = window.navigator.userAgent.toLowerCase();
        //var query_str = window.location.href;
      	//if (query_str.indexOf('debug=true') > 0) {
         // document.writeln('<script src="https://cdn.bootcss.com/vConsole/3.2.0/vconsole.min.js"' + '>' + '<' + '/' + 'script>');
         // setTimeout(() => {
         // var vConsole = new VConsole();
          //console.log('VConsole is cool');
         // }, 500)
    //  }
</script>