rem.js 1.6 KB

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