1 | function getPixelSize(element, style, property, fontSize) {
|
2 | var sizeWithSuffix = style[property],
|
3 | size = parseFloat(sizeWithSuffix),
|
4 | suffix = sizeWithSuffix.split(/\d/)[0],
|
5 | rootSize
|
6 |
|
7 | fontSize =
|
8 | fontSize != null
|
9 | ? fontSize
|
10 | : /%|em/.test(suffix) && element && element.parentElement
|
11 | ? getPixelSize(
|
12 | element.parentElement,
|
13 | element.parentElement.currentStyle,
|
14 | "fontSize",
|
15 | null
|
16 | )
|
17 | : 16
|
18 | rootSize =
|
19 | property == "fontSize"
|
20 | ? fontSize
|
21 | : /width/i.test(property)
|
22 | ? element.clientWidth
|
23 | : element.clientHeight
|
24 |
|
25 | return suffix == "em"
|
26 | ? size * fontSize
|
27 | : suffix == "in"
|
28 | ? size * 96
|
29 | : suffix == "pt"
|
30 | ? size * 96 / 72
|
31 | : suffix == "%"
|
32 | ? size / 100 * rootSize
|
33 | : size
|
34 | }
|
35 |
|
36 | function setShortStyleProperty(style, property) {
|
37 | var borderSuffix = property == "border" ? "Width" : "",
|
38 | t = property + "Top" + borderSuffix,
|
39 | r = property + "Right" + borderSuffix,
|
40 | b = property + "Bottom" + borderSuffix,
|
41 | l = property + "Left" + borderSuffix
|
42 |
|
43 | style[property] = (((style[t] == style[r]) == style[b]) == style[l]
|
44 | ? [style[t]]
|
45 | : style[t] == style[b] && style[l] == style[r]
|
46 | ? [style[t], style[r]]
|
47 | : style[l] == style[r]
|
48 | ? [style[t], style[r], style[b]]
|
49 | : [style[t], style[r], style[b], style[l]]
|
50 | ).join(" ")
|
51 | }
|
52 |
|
53 | function CSSStyleDeclaration(element) {
|
54 | var currentStyle = element.currentStyle,
|
55 | style = this,
|
56 | fontSize = getPixelSize(element, currentStyle, "fontSize", null)
|
57 |
|
58 | for (property in currentStyle) {
|
59 | if (
|
60 | /width|height|margin.|padding.|border.+W/.test(property) &&
|
61 | style[property] !== "auto"
|
62 | ) {
|
63 | style[property] =
|
64 | getPixelSize(element, currentStyle, property, fontSize) + "px"
|
65 | } else if (property === "styleFloat") {
|
66 | style["float"] = currentStyle[property]
|
67 | } else {
|
68 | style[property] = currentStyle[property]
|
69 | }
|
70 | }
|
71 |
|
72 | setShortStyleProperty(style, "margin")
|
73 | setShortStyleProperty(style, "padding")
|
74 | setShortStyleProperty(style, "border")
|
75 |
|
76 | style.fontSize = fontSize + "px"
|
77 |
|
78 | return style
|
79 | }
|
80 |
|
81 | CSSStyleDeclaration.prototype = {
|
82 | constructor: CSSStyleDeclaration,
|
83 | getPropertyPriority: function() {},
|
84 | getPropertyValue: function(prop) {
|
85 | return this[prop] || ""
|
86 | },
|
87 | item: function() {},
|
88 | removeProperty: function() {},
|
89 | setProperty: function() {},
|
90 | getPropertyCSSValue: function() {}
|
91 | }
|
92 |
|
93 | export function getCompStyle(element) {
|
94 | if (window.getComputedStyle) return window.getComputedStyle(element)
|
95 | return new CSSStyleDeclaration(element)
|
96 | }
|