-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResponsiveAdjust.js
86 lines (70 loc) · 2.19 KB
/
ResponsiveAdjust.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
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
const Options = {
minWidth: 480,
maxWidth: 1365,
measure: "rem",
}
const CSSDeclarations = [
{
selector: ":root",
propAndValue: [
{ property: "--xlarge", min: 2.5, max: 5 },
{ property: "--large", min: 1.7, max: 3.4 },
],
},
{
selector: "h1",
propAndValue: [
{ property: "margin-bottom", min: 1, max: 2 }
],
},
{
selector: "div",
propAndValue: [
{ property: "width", min: 30, max: 60 },
{ property: "height", min: 12.5, max: 25 },
],
},
]
const ResponsiveAdjust = {
createStyleEl() {
const styleEl = document.createElement("style")
styleEl.setAttribute("id", "responsive-adjust")
document.querySelector("head").appendChild(styleEl)
styleEl.insertAdjacentHTML("beforebegin", "<!-- Style injected by ResponsiveAdjust (github.com/ruuuff/responsive-adjust) -->")
},
scale(num, in_min, in_max, out_min, out_max) {
const percentage = (num - in_min) / (in_max - in_min)
let value = percentage * (out_max - out_min) + out_min
value < out_min ? value = out_min : value
value > out_max ? value = out_max : value
return value
},
callScaleWithParameters: (min, max) => ResponsiveAdjust.scale(
Number(document.documentElement.clientWidth),
Number(Options.minWidth),
Number(Options.maxWidth),
Number(min),
Number(max)
),
formatSize: sizeToFormat => parseFloat(sizeToFormat.toFixed(3)),
innerStyles() {
const style = document.querySelector("head style#responsive-adjust")
style.innerHTML = ""
for (const [index, { selector, propAndValue }] of CSSDeclarations.entries()) {
style.insertAdjacentHTML("beforeend", `${selector} {`)
for (const { property, min, max } of propAndValue) {
const scaledValue = this.callScaleWithParameters(min, max)
const size = this.formatSize(scaledValue)
style.insertAdjacentHTML("beforeend",` ${property}: ${size + Options.measure};`)
}
style.insertAdjacentHTML("beforeend", index !== CSSDeclarations.length - 1 ? `}
` : `}`)
}
},
start() {
this.createStyleEl()
this.innerStyles()
window.addEventListener("resize", () => this.innerStyles())
},
};
ResponsiveAdjust.start()