rem.js 1.7 KB

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