rem.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. (function (designWidth, maxWidth) {
  2. var doc = document;
  3. var win = window;
  4. var docEl = doc.documentElement;
  5. var tid;
  6. var rootItem, rootStyle;
  7. function refreshRem() {
  8. var width = docEl.getBoundingClientRect().width;
  9. if (!maxWidth) {
  10. maxWidth = 540;
  11. };
  12. if (width > maxWidth) {
  13. width = maxWidth;
  14. }
  15. //与淘宝做法不同,直接采用简单的rem换算方法1rem=100px
  16. var rem = width * 100 / designWidth;
  17. //兼容UC开始
  18. rootStyle = "html{font-size:" + rem + 'px !important}';
  19. rootItem = document.getElementById('rootsize') || document.createElement("style");
  20. if (!document.getElementById('rootsize')) {
  21. document.getElementsByTagName("head")[0].appendChild(rootItem);
  22. rootItem.id = 'rootsize';
  23. }
  24. if (rootItem.styleSheet) {
  25. rootItem.styleSheet.disabled || (rootItem.styleSheet.cssText = rootStyle)
  26. } else {
  27. try { rootItem.innerHTML = rootStyle } catch (f) { rootItem.innerText = rootStyle }
  28. }
  29. //兼容UC结束
  30. docEl.style.fontSize = rem + "px";
  31. };
  32. refreshRem();
  33. win.addEventListener("resize", function () {
  34. clearTimeout(tid); //防止执行两次
  35. tid = setTimeout(refreshRem, 300);
  36. }, false);
  37. win.addEventListener("pageshow", function (e) {
  38. if (e.persisted) { // 浏览器后退的时候重新计算
  39. clearTimeout(tid);
  40. tid = setTimeout(refreshRem, 300);
  41. }
  42. }, false);
  43. if (doc.readyState === "complete") {
  44. doc.body.style.fontSize = "16px";
  45. } else {
  46. doc.addEventListener("DOMContentLoaded", function (e) {
  47. doc.body.style.fontSize = "16px";
  48. }, false);
  49. }
  50. })(750, 750);