-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomputeRootSize.js
57 lines (55 loc) · 2.24 KB
/
computeRootSize.js
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
/*
# 按照宽高比例设定html字体, width=device-width initial-scale=1版
# @pargam win 窗口window对象
# @pargam option{
designWidth: 设计稿宽度,必须
designHeight: 设计稿高度,不传的话则比例按照宽度来计算,可选
designFontSize: 设计稿宽高下用于计算的字体大小,默认20,可选
callback: 字体计算之后的回调函数,可选
}
# return Boolean;
# ps:请尽量第一时间运行此js计算字体
*/
function computeRootSize(win, option) {
var count = 0,
designWidth = option.designWidth,
designHeight = option.designHeight || 0,
designFontSize = option.designFontSize || 20,
callback = option.callback || null,
root = document.documentElement,
body = document.body,
rootWidth, newSize, t, self;
root.style.width = "100%";
//返回root元素字体计算结果
function _getNewFontSize() {
var scale = designHeight !== 0 ? Math.min(win.innerWidth / designWidth, win.innerHeight / designHeight) : win.innerWidth / designWidth;
return parseInt( scale * 10000 * designFontSize ) / 10000;
}
!function () {
rootWidth = root.getBoundingClientRect().width;
//self = self ? self : arguments.callee;
//如果此时屏幕宽度不准确,就尝试再次获取分辨率,只尝试20次,否则使用win.innerWidth计算
if( rootWidth !== win.innerWidth && count < 20 ) {
win.setTimeout(function () {
count++;
computeRootSize(win, option);
}, 0);
} else {
newSize = _getNewFontSize();
//如果css已经兼容当前分辨率就不管了
if( newSize + 'px' !== getComputedStyle(root)['font-size'] ) {
root.style.fontSize = newSize + "px";
return callback && callback(newSize);
}
}
}();
//横竖屏切换的时候改变fontSize,根据需要选择使用
win.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
clearTimeout(t);
t = setTimeout(function () {
computeRootSize(win, option);
}, 300);
}, false);
}
module.exports = computeRootSize