css3 rem的理解

2018-12-06  本文已影响0人  清汤饺子

对应rem的单位是这么理解就特别简单。
html的font-size为a px。1rem = a px;
现在有张320px的设计图。我们分为32等份。
那么我的1rem = 320/32 = 10px;
公式为:
html.style.fontSize = 10px * (屏幕宽度/320);

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style type="text/css">
    div{
        width: 1rem;
        height: 100px;
        background: red;
    }
</style>
<body>
    <div></div>
</body>
<script>
    (function(){
      if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)){
        //document.write('<link href="../css/m.css" rel="stylesheet" />');
        (function (win, doc) {
          if (!win.addEventListener) return;
          function setFont() {
            var html = document.documentElement; 
            var k =375;//设计图宽度
            var a = 100;//在设计图中的比例是1rem = 100px;
            console.log(html.clientWidth);
            html.style.fontSize = html.clientWidth / k * a + "px";
          }
          setFont();
          setTimeout(function () {   setFont(); }, 300);
          doc.addEventListener('DOMContentLoaded', setFont, false);
          win.addEventListener('resize', setFont, false);
          win.addEventListener('load', setFont, false);
        })(window, document);
      }
    }());
</script>
</html>
上一篇下一篇

猜你喜欢

热点阅读