rem.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 = (2560 * 100) / 2560;
  11. //兼容UC开始
  12. rootStyle = 'html{font-size:' + rem + 'px !important}';
  13. rootItem =
  14. document.getElementById('rootsize') || document.createElement('style');
  15. if (!document.getElementById('rootsize')) {
  16. document.getElementsByTagName('head')[0].appendChild(rootItem);
  17. rootItem.id = 'rootsize';
  18. }
  19. if (rootItem.styleSheet) {
  20. rootItem.styleSheet.disabled || (rootItem.styleSheet.cssText = rootStyle);
  21. } else {
  22. try {
  23. rootItem.innerHTML = rootStyle;
  24. } catch (f) {
  25. rootItem.innerText = rootStyle;
  26. }
  27. }
  28. //兼容UC结束
  29. docEl.style.fontSize = rem + 'px';
  30. }
  31. refreshRem();
  32. win.addEventListener(
  33. 'resize',
  34. function () {
  35. clearTimeout(tid); //防止执行两次
  36. tid = setTimeout(refreshRem, 300);
  37. },
  38. false,
  39. );
  40. win.addEventListener(
  41. 'pageshow',
  42. function (e) {
  43. if (e.persisted) {
  44. // 浏览器后退的时候重新计算
  45. clearTimeout(tid);
  46. tid = setTimeout(refreshRem, 300);
  47. }
  48. },
  49. false,
  50. );
  51. if (doc.readyState === 'complete') {
  52. doc.body.style.fontSize = '16px';
  53. } else {
  54. doc.addEventListener(
  55. 'DOMContentLoaded',
  56. function (e) {
  57. doc.body.style.fontSize = '16px';
  58. },
  59. false,
  60. );
  61. }
  62. })();