仅使用JavaScript单击按钮即可增加字体大小

asc*_*dio 3 javascript button font-size

我试图通过单击按钮来增加字体大小。我有第一个工作的人,但我无法绕过第二个工作。第二个,每次单击将使字体增加1px(我非常困惑):

<input type="button" value="Increase Font Size 100px" onclick="increaseFontSizeBy100px()">
<p id="a">Font Size</p>

<input type="button" value="Increase Font Size 1px" onclick="increaseFontSizeBy1px()">
<p id="b">Font Size by 1 Pixel</p>

<script> 
    function increaseFontSizeBy100px() {
        document.getElementById('a').style.fontSize = "100px";
    }

    function increaseFontSizeBy1px() {
        var font = document.getElementById('b').style.fontSize;            
        font++;
    }
</script>
Run Code Online (Sandbox Code Playgroud)

小智 9

将您的函数更改为下面的代码,然后看看会发生什么:

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';
}
Run Code Online (Sandbox Code Playgroud)

注意:如您所见,两个函数都有很多重复项。因此,如果您是我,我将更改此功能以将字体大小增加给定值(在本例中为int)。

那么,我们能做些什么呢?我认为我们应该将这些功能转变为更通用的功能。

看一下下面的代码:

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';
}
Run Code Online (Sandbox Code Playgroud)

现在,例如,在您的“增加字体大小1px”按钮中,应输入以下内容:

<input type="button" value="Increase Font Size 1px" onclick="increaseFontSize("b", 1)">
<p id="b">Font Size by 1 Pixel</p>
Run Code Online (Sandbox Code Playgroud)

但是,如果我们想要“减小字体大小1px”,该怎么办?我们用-1而不是1来调用函数。

<input type="button" value="Decrease Font Size 1px" onclick="increaseFontSize("b", -1)">
<p id="b">Font Size by -1 Pixel</p>
Run Code Online (Sandbox Code Playgroud)

我们也解决了减小字体大小的问题。但是,我会将函数名称更改为一个更通用的名称,并在我将创建的两个函数中都将其调用:crementFontSize(id,creaseFactor)reducingFontSize(id,reducingFactor)

而已。