首页 > 技术文章 > 移动端适配js

afang 2016-05-30 17:37 原文

 <script>
        (function (doc, win) {
          var docEl = doc.documentElement,
            resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
            recalc = function () {
              var clientWidth = docEl.clientWidth;
              if (!clientWidth) return;
              docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
            };

          if (!doc.addEventListener) return;
          win.addEventListener(resizeEvt, recalc, false);
          doc.addEventListener('DOMContentLoaded', recalc, false);
        })(document, window);
    </script> 
 
<script>
var docEl = doc.documentElement,
              isIOS = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
              dpr = isIOS ? Math.min(win.devicePixelRatio, 3) : 1,
              dpr = window.top === window.self ? dpr : 1, //被iframe引用时,禁止缩放
              resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
          docEl.dataset.dpr = dpr;
          var recalc = function() {
              var width = docEl.clientWidth;
              if (width / dpr > 640) {
                  width = 640 * dpr;
              }
              docEl.dataset.width = width;
              docEl.dataset.percent = 100 * (width / 640);
              docEl.style.fontSize = 100 * (width / 640) + 'px';
          };
          recalc()
          if (!doc.addEventListener) return;
          win.addEventListener(resizeEvt, recalc, false);
      })(document, window);
 
</script>

推荐阅读