手機端rem適應

來源:互聯網
上載者:User

標籤:loaded   data   計算   hone   user   line   gen   max   event   

這段時間做了幾個手機版的項目,因為沒有用架構,所以用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】

 

手機端rem適應

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.