JavaScript动态设置根元素的rem

1. 什么是rem

说到rem自然就会想到em,我们知道em是相对于父元素的字体大小的单位,那么rem则是相对于根元素也就是元素的字体大小的单位。

2.如何用rem解决移动端适配

在这里插入图片描述
通过这张图我们就可以观察到,div的宽度和高度是根据根元素()来决定的,根元素的字体大小为100px,然后给div的宽度和高度设置为2rem、1rem,最后生成的div的宽度为200px、高度为100px。

3.通过JavaScript动态设置rem

不同浏览器根标签的默认字体大小不一样,所以需要JavaScript动态设置rem。

方案一:

<script type="text/javascript">
  window.addEventListener(('orientationchange' in window ? 'orientationchange' : 'resize'), (function() {
    function c() {
      var d = document.documentElement;
      var cw = d.clientWidth || 750;
      d.style.fontSize = (20 * (cw / 375)) > 40 ? 40 + 'px' : (20 * (cw / 375)) + 'px';
    }
    c();
    return c;
  })(), false);
</script>
<style type="text/css">
  html{font-size:10px}
  *{margin:0;}
</style>

设计稿中标注此div的width:750px;height:200px;
换算为rem,即为width:18.75rem,height:5rem;
此时 1rem = 40px;将设计稿标注的宽高除以40即可得到rem的值。

<div style="width:18.75rem;height:5rem;background:#f00;color:#fff;text-align:center;">
    此时在iPhone6上测试,width:375px,也即width:100%</div>

方案二:

<script type="text/javascript">
  !(function(doc, win) {
    var docEle = doc.documentElement, //获取html元素
      event = "onorientationchange" in window ? "orientationchange" : "resize", //判断是屏幕旋转还是resize;
      fn = function() {
        var width = docEle.clientWidth;
        width && (docEle.style.fontSize = 10 * (width / 375) + "px"); //设置html的fontSize,随着event的改变而改变。
      };

    win.addEventListener(event, fn, false);
    doc.addEventListener("DOMContentLoaded", fn, false);

  }(document, window));
</script>
<style type="text/css">
  html {
    font-size: 10px;
  }
  *{
      margin: 0;
  }
</style>

设计稿中标注此div的width:750px;height:200px;
换算为rem,即为width:37.5rem,height:10rem;
此时 1rem = 20px;将设计稿标注的宽高除以20即可得到rem的值。

<div style="width:37.5rem;height:10rem;background:#f00;color:#fff;text-align:center;">
    test
</div>
发布了75 篇原创文章 · 获赞 280 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/liuyifeng0000/article/details/104828554