/
getComputedStyles.ts
51 lines (46 loc) · 1.85 KB
/
getComputedStyles.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
import findClosestElementAncestor from './findClosestElementAncestor';
/**
* Get computed styles of a node
* @param node The node to get computed styles from
* @param styleNames Names of style to get, can be a single name or an array.
* Default value is font-family, font-size, color, background-color
* @returns An array of the computed styles
*/
export default function getComputedStyles(
node: Node,
styleNames: string | string[] = ['font-family', 'font-size', 'color', 'background-color']
): string[] {
const element = findClosestElementAncestor(node);
const result: string[] = [];
styleNames = Array.isArray(styleNames) ? styleNames : [styleNames];
if (element) {
const win = element.ownerDocument.defaultView || window;
const styles = win.getComputedStyle(element);
if (styles) {
for (const style of styleNames) {
let value = styles.getPropertyValue(style) || '';
value = style != 'font-family' ? value.toLowerCase() : value;
value = style == 'font-size' ? px2Pt(value) : value;
result.push(value);
}
}
}
return result;
}
/**
* A shortcut for getComputedStyles() when only one style is to be retrieved
* @param node The node to get style from
* @param styleName The style name
* @returns The style value
*/
export function getComputedStyle(node: Node, styleName: string): string {
return getComputedStyles(node, styleName)[0] || '';
}
function px2Pt(px: string) {
if (px && px.indexOf('px') == px.length - 2) {
// Edge may not handle the floating computing well which causes the calculated value is a little less than actual value
// So add 0.05 to fix it
return Math.round(parseFloat(px) * 75 + 0.05) / 100 + 'pt';
}
return px;
}