I write following function to return the width and height of a text:
JavaScript
x
24
24
1
function size_calculation(word,fontSize) {
2
const div = document.body.appendChild(document.createElement('div'));
3
div.textContent = word;
4
div.style.cssText = `
5
font-size:${fontSize}px;
6
width:auto;
7
position:absolute;
8
visibility:hidden;
9
`
10
const computed_styles = window.getComputedStyle(div);
11
//return the expected height
12
console.log(computed_styles.getPropertyValue('height'))
13
14
div.remove();
15
16
//return nothing
17
console.log(computed_styles,computed_styles.getPropertyValue('height'))
18
19
return ({
20
height: computed_styles["height"],
21
width:computed_styles["width"]
22
})
23
}
24
console.log(size_calculation("hi",15))
I am quite confused why after I remove the div
, all styles’ property in the computed_styles
will become ""
nothing, but before I remove the div
, all styles’ property in the computed_styles
has something different than ""
.
In my understanding, the value for variable will not be changed and is static unless we write any update or reassign statement once declared (AM I Wrong?)
Why the computed_styles will be automatically update?
Thank you!
P.S: not asking for solution (solution quite easy), but curious why.
Advertisement
Answer
See MDN
Return value: A live CSSStyleDeclaration object, which updates automatically when the element’s styles are changed.
Note the word live.