View on GitHub

Cycle263 Blog

Stay hungry, stay foolish.

手机端自动适配

如今手机都是高倍屏,即一个css像素会有多个物理像素,dpr用来表示一个css像素用多少物理像素来表示。

window.devicePixelRedio;   // 1 

大厂的适配方案

! function (window, t) {
  var docuEle = document.documentElement,
    dpr = window.devicePixelRatio || 1;

  function i() {
    var w = docuEle.clientWidth / 3.75;
    docuEle.style.fontSize = w + "px"
  }
  if (function e() {
      document.body ? document.body.style.fontSize = "16px" : 
      document.addEventListener("DOMContentLoaded", e)
    }(), i(), window.addEventListener("resize", i), window.addEventListener("pageshow", function (e) {
      window.persisted && i()
    }), 2 <= dpr) {
    var o = document.createElement("body"),
      a = document.createElement("div");
    a.style.border = ".5px solid transparent", o.appendChild(a), docuEle.appendChild(o), 1 === a.offsetHeight && docuEle.classList.add("hairlines"), docuEle.removeChild(o)
  }
}(window, document)
html {
    font-size: 13.33333vw
}
@media screen and (max-width: 320px) {
    html {
        font-size:42.667px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 321px) and (max-width:360px) {
    html {
        font-size:48px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 361px) and (max-width:375px) {
    html {
        font-size:50px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 376px) and (max-width:393px) {
    html {
        font-size:52.4px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 394px) and (max-width:412px) {
    html {
        font-size:54.93px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 413px) and (max-width:414px) {
    html {
        font-size:55.2px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 415px) and (max-width:480px) {
    html {
        font-size:64px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 481px) and (max-width:540px) {
    html {
        font-size:72px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 541px) and (max-width:640px) {
    html {
        font-size:85.33px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 641px) and (max-width:720px) {
    html {
        font-size:96px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 721px) and (max-width:768px) {
    html {
        font-size:102.4px;
        font-size: 13.33333vw
    }
}
@media screen and (min-width: 769px) {
    html {
        font-size:102.4px;
        font-size: 13.33333vw
    }
}