屏幕自适应rem计算方法

2020-06-17  本文已影响0人  芸芸众生ing

换算后 1rem == 1px;直接根据设计稿尺寸即可

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="icon" href="/favicon.ico">
  <title>document</title>

</head>

<body style="max-width: 750px;">
  <script>
    function autoDpr() {
      let Pixel = 750; // 设计稿宽度
      let Dpr = 1;
      let wWidth = document.documentElement.clientWidth;
      if (window.devicePixelRatio) Dpr = window.devicePixelRatio;
      if (wWidth > Pixel) wWidth = Pixel;
      let size = (wWidth / Pixel);
      document.querySelector('html').setAttribute('data-dpr', Dpr);
      document.querySelector('html').setAttribute('style', "font-size:" + size + "px !important");
      document.querySelector('body').setAttribute('style', 'margin:auto;max-width:' + Pixel + 'px !important')
    }
    autoDpr();
    window.addEventListener('resize', autoDpr);
    window.addEventListener('pageshow', autoDpr);
  </script>
  <div style="font-size: 14rem;">字体大小rem</div>
  <div style="font-size: 14px;">字体大小px</div>
  <div style="width: 375rem;height:100rem;background:#eee"></div>
  <div style="width: 750rem;height:100rem;background:#444"></div>
</body>

</html>
上一篇下一篇

猜你喜欢

热点阅读