31 在移动端中怎样初始化根元素的字体大小

一个简易版的初始化根元素字体大小。

页面开头处引入下面这段代码,用于动态计算font-size

(假设你需要的1rem = 20px)

    (function () {
      var html = document.documentElement;
      function onWindowResize() {
        html.style.fontSize = html.getBoundingClientRect().width / 20 + 'px';
      }
      window.addEventListener('resize', onWindowResize);
      onWindowResize();
    })();
  • document.documentElement:获取document的根元素
  • html.getBoundingClientRect().width:获取html的宽度(窗口的宽度)
  • 监听windowresize事件

一般还需要配合一个meta头:

    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-sacle=1.0, maximum-scale=1.0, user-scalable=no" />
Last Updated:
Contributors: leeguooooo