手机端rem适应

这段时间做了几个手机版的项目,因为没有用框架,所以用rem来做适应,下面就分享一下

//第一种是比较简单的代码

(function(win) {
  resizeRoot();
  function resizeRoot() {
    var wWidth = document.documentElement.clientWidth;
    if (wWidth > 640) wWidth = 640;
    else if (wWidth < 320) wWidth = 320;
    document.documentElement.style.fontSize = wWidth * 0.0625 + 'px'
  }
  window.onresize = resizeRoot
})(window);

 

//第二种

!function (window) {
  /* 设计图文档宽度 */
  var docWidth = 750;
  var doc = window.document,
    docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
  var recalc = (function refreshRem () {
    var clientWidth = docEl.getBoundingClientRect().width;
    /* 8.55:小于320px不再缩小,11.2:大于420px不再放大 */
    docEl.style.fontSize = Math.max(Math.min(20 * (clientWidth / docWidth), 11.2), 8.55) * 5 + 'px';
    return refreshRem;
  })();
  /* 添加倍屏标识,安卓为1 */
  docEl.setAttribute('data-dpr', window.navigator.appVersion.match(/iphone/gi) ? window.devicePixelRatio : 1);

  if (/iP(hone|od|ad)/.test(window.navigator.userAgent)) {
  /* 添加IOS标识 */
    doc.documentElement.classList.add('ios');
  /* IOS8以上给html添加hairline样式,以便特殊处理 */
  if (parseInt(window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/)[1], 10) >= 8)
    doc.documentElement.classList.add('hairline');
  }
  if (!doc.addEventListener) return;
    window.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
  }(window);

 

//引用这第二的就比较容易计算,设计图尺寸以px / 100 = 实际rem 【例如 100px = 1rem ,24px=0.24rem】

 

posted @ 2017-09-14 12:09  Lin宇  阅读(505)  评论(0编辑  收藏  举报