用js设置font-size

动态计算html的font-size

  1. (function (doc, win) {
  2. var docEl = doc.documentElement,
  3. isIOS = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
  4. dpr = isIOS ? Math.min(win.devicePixelRatio, 3) : 1,
  5. dpr = window.top === window.self ? dpr : 1, //被iframe引用时,禁止缩放
  6. dpr = 1,
  7. scale = 1 / dpr,
  8. resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
  9. docEl.dataset.dpr = dpr;
  10. var metaEl = doc.createElement('meta');
  11. metaEl.name = 'viewport';
  12. metaEl.content = 'initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale;
  13. docEl.firstElementChild.appendChild(metaEl);
  14. var recalc = function() {
  15. var width = docEl.clientWidth;
  16. if (width / dpr > 750) {
  17. width = 750 * dpr;
  18. }
  19. // 乘以100,px : rem = 100 : 1
  20. docEl.style.fontSize = 100* (width / 750) + 'px';
  21. };
  22. recalc()
  23. if (!doc.addEventListener) return;
  24. win.addEventListener(resizeEvt, recalc, false);
  25. })(document, window);

引入前:

  1. body {
  2. width: 750px;
  3. height: 640px;
  4. }

引入后:

  1. body {
  2. width: 7.5rem;
  3. height: 6.4rem;
  4. }

用媒体查询设置font-size

  1. //SUI css源码
  2. html {
  3. font-size: 20px
  4. }
  5. @media only screen and (min-width: 400px) {
  6. html {
  7. font-size: 21.33px !important
  8. }
  9. }
  10. @media only screen and (min-width: 414px) {
  11. html {
  12. font-size: 22.08px !important
  13. }
  14. }
  15. @media only screen and (min-width: 480px) {
  16. html {
  17. font-size: 25.6px !important
  18. }
  19. }

用媒体查询设置html的font-size更简单,但是不能准确还原设计图。