我如何动态地增加字体大小与Javascript和为什么是我目前的功能不工作

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

本文关键字:为什么 Javascript 目前 工作 功能 何动态 动态 字体 增加      更新时间:2023-09-26

我试图使用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>

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

这个脚本应该可以运行:

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

我发现了这个惊人的脚本:https://github.com/simplefocus/FlowType.JS

演示:http://simplefocus.com/flowtype/demo.html

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