Increase the font size with a click of a button using only JavaScript

前端 未结 6 805
悲&欢浪女
悲&欢浪女 2020-12-09 22:45

I\'m attempting to increase the font size with the click of a button. I have got the first one to work but I can\'t get my head around the second one. The second one, every

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 23:08

    Change your function to as in the code below and see what happens:

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

    Note: as you can see, there are a lot of duplication in both functions. Therefore, if I were you, I would change this function to increase the fontsize by a given value(in this case, an int).

    So, what we can do about it? I think we should turn these functions into a more generic one.

    Take a look at the code below:

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

    Now, for example, in your button "Increase Font Size 1px", you should put something like:

    
    

    Font Size by 1 Pixel

    But, if we want a "Decrease Font Size 1px", what we can do? We call the function with -1 rather than with 1.

    
    

    Font Size by -1 Pixel

    We solve the Decrease Font Size problem as well. However, I would change the function name to a more generic one and call it in both two functions that I would create: increaseFontSize(id, increaseFactor) and decreaseFontSize(id, decreaseFactor).

    That's it.

提交回复
热议问题