笔记 rem.js 1rem=100px

408 阅读1分钟

meta标签

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./js/rem.js"></script>

css 媒体查询

px值使用 rem

@media screen and (max-width: 750px) {

}

rem.js

(function (doc, win) {
  var docEl = doc.documentElement,
    resizeEvt = "orientationchange" in window ? "orientationchange" : "resize"
  var designWidth = 750;

  recalc = function () {
    var html = document.getElementsByTagName("html")[0];

    var clientWidth = docEl.clientWidth;
    if (!clientWidth) return;
    if (clientWidth >= designWidth) {
      html.setAttribute("style", "");
      return
      docEl.style.fontSize = "100px";
    } else {
      docEl.style.fontSize = 100 * (clientWidth / designWidth) + "px";
    }

    var settedFs = (settingFs = parseInt(100 * (clientWidth / designWidth)));
    var whileCount = 0;

    while (true) {
      var realFs = parseInt(window.getComputedStyle(html).fontSize);
      var delta = realFs - settedFs;
      //不相等
      if (Math.abs(delta) >= 1) {
        if (delta > 0) settingFs--;
        else settingFs++;
        html.setAttribute("style", "font-size:" + settingFs + "px!important");
      } else break;
      if (whileCount++ > 100) break;
    }
  };

  if (!doc.addEventListener) return;
  win.addEventListener(resizeEvt, recalc, false);
  doc.addEventListener("DOMContentLoaded", recalc, false);
})(document, window);