rem.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 = localStorage.width;
  9. if (!width) return;
  10. //与淘宝做法不同,直接采用简单的rem换算方法1rem=100px
  11. var rem = (width * 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. window.refreshRem = refreshRem;
  64. window.addEventListener('storage', (e) => {
  65. console.log(e);
  66. if (e.key == 'width') {
  67. refreshRem();
  68. }
  69. });
  70. })();