如何使用 Javascript 动态增加字体大小,为什么我当前的功能不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16282633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:02:55  来源:igfitidea点击:

How can I dynamically increase font size with Javascript and why is my current function not working?

javascripthtmlcssfont-size

提问by Kenny Johnson

I'm trying to increase the font size of my page using a javascript function but it's not working. Is there a syntax problem with my code or is it not possible to do what I'm trying to do?

我正在尝试使用 javascript 函数增加页面的字体大小,但它不起作用。我的代码是否存在语法问题,或者无法执行我正在尝试执行的操作?

Javascript:

Javascript:

function changeFontSize(fontvar) {
var div = document.getElementById("webchat_history");
var currentFont = div.style.fontSize.value;

div.style.fontSize = currentFont + fontvar+ "px";
}

HTML:
<span onClick="changeFontSize(10);" style="font-size:16px;">Aa</span>

HTML:
<span onClick="changeFontSize(10);" style="font-size:16px;">Aa</span>

I want to increase it by x amount (fontvar) rather than specifying a specific font size because my font sizes are set in an external stylesheet. When/if I need to modify the stylesheets, I'd rather not have to update the Javascript too.

我想将它增加 x 数量(fontvar)而不是指定特定的字体大小,因为我的字体大小是在外部样式表中设置的。当/如果我需要修改样式表,我也不想更新 Javascript。

回答by LRA

This script should work:

这个脚本应该可以工作:

function changeFontSize(fontvar) {
    var div = document.getElementById("webchat_history");
    var currentFont = div.style.fontSize.replace("px", "");

    div.style.fontSize = parseInt(currentFont) + parseInt(fontvar) + "px";
}

回答by Kenny Johnson

After additional debugging, I realized the "id" I was using, webchat_history, was not actually an ID. It was the classfor ID history. I'm going to create additional classes and use document.getElementById('history').className = "webchat_history_medium";to change font sizes.

经过额外的调试,我意识到我使用的“id”webchat_history实际上并不是一个 ID。它是ID的history。我将创建其他类并用于document.getElementById('history').className = "webchat_history_medium";更改字体大小。