我可以编写JS代码来设置字体大小,但我想写一个函数来增加当前的字体大小。例如,它将字体大小设置为当前大小+ 1em。有可能吗?
发布于 2020-05-08 20:28:01
添加相对值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>
发布于 2020-05-08 20:19:48
您可以使用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>
发布于 2020-05-08 20:33:48
您可以获取要更新的文本的当前字体大小,添加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>
https://stackoverflow.com/questions/61678904
复制相似问题