把你的函数更改为下面的代码,看看会发生什么:
function increaseFontSizeBy100px() {
txt = document.getElementById('a');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
txt.style.fontSize = (currentSize + 100) + 'px';
}
function increaseFontSizeBy1px() {
txt = document.getElementById('b');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
txt.style.fontSize = (currentSize + 1) + 'px';
}
注意:正如您所看到的,这两个函数中存在大量重复。因此,如果我是您,我会将此函数更改为按给定值增加字体大小(在本例中为整数)。
那么,我们能做些什么呢?我认为我们应该将这些函数转换为更通用的函数。
看一下下面的代码:
function increaseFontSize(id, increaseFactor){
txt = document.getElementById(id);
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
txt.style.fontSize = (currentSize + increaseFactor) + 'px';
}
例如,在您的按钮"增加字体大小1像素"中,您应该放置类似以下内容的东西:
<input type="button" value="Increase Font Size 1px" onclick="increaseFontSize("b", 1)">
<p id="b">Font Size by 1 Pixel</p>
但是,如果我们想要一个 "缩小字体大小1像素" ,该怎么办?我们使用-1而不是1来调用函数。
<input type="button" value="Decrease Font Size 1px" onclick="increaseFontSize("b", -1)">
<p id="b">Font Size by -1 Pixel</p>
我们也解决了“减小字体大小”的问题。不过,我会将函数名更改为一个更通用的名称,并在我创建的两个函数中调用它: “increaseFontSize(id, increaseFactor)” 和 “decreaseFontSize(id, decreaseFactor)”。
就这样。
document.getElementById('b').style.fontSize
是一个字符串,而不是你可以递增的数字,即使你可以递增,你实际上也没有“设置”字体,你只是在递增某个变量。 - Sebastian Simon