forked from MichealWayne/fe-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrem.ts
124 lines (108 loc) · 2.88 KB
/
rem.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/**
* @model rem
* @desc 单位1rem = 75px(mobile);1rem = 54px(pc)。(当window.norem存在时,则不设置rem单位)
* @alias window.flexible
* @property {Number} dpr 设备屏幕分辨率
* @property {Number} rem rem比例
* @Date 2020-04-11 21:55:46
* @LastEditTime 2023-02-21 11:12:35
*/
import { PlainObject } from 'utils';
import { isPC } from './platform';
const remRate = 1;
declare global {
interface Window {
norem?: boolean;
flexible: any;
}
}
(function (win) {
// no rem set
if (window.norem) return false;
const doc = win.document;
const docEl = doc.documentElement;
const dpr = 1;
let tid: number;
const flexible: PlainObject = {};
if (isPC()) {
docEl.style.fontSize = '54px';
return false;
}
/**
* @function refreshRem
* @description **window.flexible.refreshRem()**。重新根据屏幕调整rem
* @example
* window.flexible.refreshRem();
*/
function refreshRem() {
let { width } = docEl.getBoundingClientRect();
width = width > 540 ? 540 : width;
const rem = (width / 10) * remRate;
docEl.style.fontSize = `${rem}px`;
flexible.rem = rem;
flexible.oriRem = width / 10;
}
win.addEventListener(
'resize',
function () {
clearTimeout(tid);
tid = win.setTimeout(refreshRem, 300);
},
false
);
win.addEventListener(
'pageshow',
function (e) {
if (e.persisted) {
clearTimeout(tid);
tid = win.setTimeout(refreshRem, 300);
}
},
false
);
if (doc.readyState === 'complete') {
refreshRem();
} else {
doc.addEventListener(
'DOMContentLoaded',
function () {
refreshRem();
},
false
);
}
refreshRem();
flexible.dpr = dpr;
flexible.refreshRem = refreshRem;
/**
* @function rem2px
* @description **window.flexible.rem2px(d)**。rem单位转px
* @param {Number | String} remVal rem值
* @return {String} 转换后px值
* @example
* window.flexible.rem2px('1rem'); // '75px'
*/
flexible.rem2px = (remVal: string | number) => {
let val: string | number = parseFloat(remVal as string) * (Number(flexible.rem) || 0);
if (typeof remVal === 'string' && remVal.match(/rem$/)) {
val = `${val}px`;
}
return val;
};
/**
* @function px2rem
* @description **window.flexible.px2rem(d)**。rem单位转px
* @param {Number | String} pxVal px值
* @return {String} 转换后rem值
* @example
* window.flexible.rem2px('75px'); // '1rem'
*/
flexible.px2rem = (pxVal: string) => {
let val: string | number = parseFloat(pxVal) / (Number(flexible.rem) || 0);
if (typeof pxVal === 'string' && pxVal.match(/px$/)) {
val = `${val}rem`;
}
return val;
};
win.flexible = flexible;
})(window);