我撰寫了以下函式來回傳文本的寬度和高度:
function size_calculation(word,fontSize) {
const div = document.body.appendChild(document.createElement('div'));
div.textContent = word;
div.style.cssText = `
font-size:${fontSize}px;
width:auto;
position:absolute;
visibility:hidden;
`
const computed_styles = window.getComputedStyle(div);
//return the expected height
console.log(computed_styles.getPropertyValue('height'))
div.remove();
//return nothing
console.log(computed_styles,computed_styles.getPropertyValue('height'))
return ({
height: computed_styles["height"],
width:computed_styles["width"]
})
}
console.log(size_calculation("hi",15))
我很困惑為什么在我洗掉div, 所有樣式的屬性computed_styles后將變為""空,但在我洗掉之前div,所有樣式的屬性computed_styles與"".
據我了解,變數的值不會改變并且是靜態的,除非我們在宣告后撰寫任何更新或重新分配陳述句(我錯了嗎?)
為什么 computed_styles 會自動更新?
謝謝!
PS:不要求解決方案(解決方案很容易),但很好奇為什么。
uj5u.com熱心網友回復:
見MDN
回傳值:一個實時的 CSSStyleDeclaration 物件,當元素的樣式改變時它會自動更新。
注意活這個詞。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479515.html
標籤:javascript html css
