rem.js 1.6 KB

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