簡體   English   中英

使用 JavaScript 將 x em 添加到字體大小?

[英]Add x em to font size with JavaScript?

我可以編寫設置字體大小的 JS 代碼,但我想編寫一個 function 來添加到當前字體大小。 例如,它將字體大小設置為當前大小 + 1em。 可能嗎?

您可以使用getComputedStyle來獲取當前大小:

 function makeFontBigger(){ var text = document.getElementById("text"); var style = window.getComputedStyle(text, null).getPropertyValue('font-size'); var fontSize = parseFloat(style); text.style.fontSize = (fontSize + 1) + 'px'; }
 <p id="text">This is a nice example.<p> <button onClick="makeFontBigger()">Make the font bigger!</button>

添加作為相對值的1em並非易事,具體取決於元素的字體大小當前基於的單位。

您可以做的是使用當前字體大小並使用calc來添加 1em,但如果原始字體大小是相對的,那么如果字體大小是基於更改的相對大小,這將不會產生預期的結果。

 function add1em() { var text = document.getElementById("text"); var fontSize = window.getComputedStyle(text, null).getPropertyValue('font-size'); text.style.fontSize = 'calc(' + fontSize + ' + 1em)'; } var text = document.getElementById("add1em").addEventListener('click', add1em, null, false);
 <p id="text">Some Text.</p> <button id="add1em">add 1 em</button>

您可以獲取要更新的文本的當前字體大小,添加 10(或您想要的任意數量),然后將其設置為新的字體大小。

 function increaseFont() { var pTag = document.querySelector(".text"); var newFont = parseInt(window.getComputedStyle(pTag).getPropertyValue('font-size')) + 10; pTag.style.fontSize = newFont.toString(10) + 'px'; }
 <p class="text">Text<p> <button onclick="increaseFont()">Increase Font</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM