移動端之js控制rem,適配字體

方法一:設置fontsize 按照iphone 5的適配  1em=10px    適配320html

// 「()()」表示自執行函數
(function (doc, win) {
  var docEl = doc.documentElement,
    // 手機旋轉事件,大部分手機瀏覽器都支持 onorientationchange 若是不支持,可使用原始的 resize
      resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
      recalc = function () {
        //clientWidth: 獲取對象可見內容的寬度,不包括滾動條,不包括邊框
        var clientWidth = docEl.clientWidth;
        if (!clientWidth) return;
        docEl.style.fontSize = 10*(clientWidth / 320) + 'px';
      };
 
  recalc();
  //判斷是否支持監聽事件 ,不支持則中止
  if (!doc.addEventListener) return;
  //註冊翻轉事件
  win.addEventListener(resizeEvt, recalc, false);
 
})(document, window);

方法二:按照iPhone6的尺寸設計    是375/25=15px瀏覽器

(function (docs, win) {
  var docEls = docs.documentElement,
  resizeEvts = 'orientationchange' in window ? 'orientationchange' : 'resize',
  recalcs = function () {

  //getBoundingClientRect()這個方法返回一個矩形對象

  window.rem = docEls.getBoundingClientRect().width/25;
  docEls.style.fontSize = window.rem + 'px';

};
  recalcs();
  if (!docs.addEventListener) return;
  win.addEventListener(resizeEvts, recalcs, false);
})(document, window);

方式三:採用mediaiphone

1 html {
 2     font - size: 20 px;
 3 }
 4 @media only screen and(min - width: 401 px) {
 5     html {
 6         font - size: 25 px!important;
 7     }
 8 }
 9 @media only screen and(min - width: 428 px) {
10     html {
11         font - size: 26.75 px!important;
12     }
13 }
14 @media only screen and(min - width: 481 px) {
15     html {
16         font - size: 30 px!important;
17     }
18 }
19 @media only screen and(min - width: 569 px) {
20     html {
21         font - size: 35 px!important;
22     }
23 }
24 @media only screen and(min - width: 641 px) {
25     html {
26         font - size: 40 px!important;
27     }
28 }
複製代碼

推薦使用的 js方式設置函數

相關文章
相關標籤/搜索