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

标签 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>

最佳答案

按照下面的代码更改您的函数,看看会发生什么:

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';
}

注意:如您所见,这两个函数中有很多重复项。因此,如果我是你,我会更改此函数以将字体大小增加给定值(在本例中为 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';
}

现在,例如,在您的按钮"Increase Font Size 1px"中,您应该输入如下内容:

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

但是,如果我们想要“减小字体大小 1px”,我们可以做什么?我们用 -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).

就是这样。

关于javascript - 仅使用 JavaScript 单击按钮即可增加字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38627822/

相关文章:

javascript - 如何在传单弹出窗口中集成 Vue 组件?

javascript - 管道内的映射被忽略并且不会触发http调用

android - 在 Android 中获取多行 TextView 的默认字体大小

iPad Safari 上的 HTML 页面字体变大

javascript - 如何在 Internet Explorer 浏览器的 JavaScript 中修复数组 indexOf()

javascript - 如何使用 jquery 检测绑定(bind)到元素的事件

java - 通过小部件中的按钮触发事件

javascript - 前进和后退按钮在插入符号位置处使用react

java - Jsoup formElement.submit().post() 未提交指定的值

android - 为什么 EM 字体在 Android 手机上超小?