移动端rem适配方案(解决1px 兼容问题)

2023-10-31

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body style="box-sizing: border-box;margin:0;padding:0">
  <div style="width:7.5rem;height:2rem;background:red"></div>
  <script>
    (function() {//解决不同手机dpr不一致的适配问题(解决了1px的问题)
          var scale = 1.0;
          if (window.devicePixelRatio === 2) {
              scale *= 0.5;
          }
          if (window.devicePixelRatio === 3) {
              scale *= 0.333333;
          }
          var meta = document.createElement('meta');
          meta.setAttribute('name', 'viewport');
          meta.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
          document.head.appendChild(meta);       
    })();
    (function (doc, win) {//解决不同手机分辨率不一致的适配问题
        var docEl = "";
        docEl = doc.documentElement, resizeEvt = "orientationchange" in window ? "orientationchange" : "resize", recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) {
                return
            } else {
                if (clientWidth > 1280) {
                    docEl.style.fontSize = 170.66+ "px"
                } else {
                    if (clientWidth < 640) {
                        docEl.style.fontSize = 85.33 + "px"
                    } else {
                        if (clientWidth <= 1280 || clientWidth >= 640) {
                            docEl.style.fontSize = (clientWidth / 750) * 100 + "px"
                        }
                    }
                }
            }
        };
        if (!doc.addEventListener) {
            return
        }
        win.addEventListener(resizeEvt, recalc, false);
        doc.addEventListener("DOMContentLoaded", recalc, false)
    })(document, window);
  </script>
</body>
</html>

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

移动端rem适配方案(解决1px 兼容问题) 的相关文章