Domanda

I'm new into programming and I was messing around with resizing my font size. But how do I do resize with + 2px and -2px for example? I can only make it now to 12px but I don't know how to keep adding on 2 pixels. Thanks in advance!

function smaller() {
    var alineas = document.getElementsByTagName('p');
    for (bla in alineas) {
        alineas[bla].style.fontSize = '5px';
    }
}

function bigger() {
    var  alineas = document.getElementsByTagName('p');
    for (alinea in alineas) {
        alineas[alinea].style.fontSize = "10px";
    }
}
È stato utile?

Soluzione

  • Don't use for..in to loop through a node list. Use a for loop instead.
  • You need to get the current font size from the element, you can use window.getComputedStyle() for this.
  • You can easily shorten your code to one function and leave the scale of font size down to a parameter.

How is the following:

function fontSize(num) {
    var alineas = document.getElementsByTagName('p');
    for (i=0; i<alineas.length; i++) {
        var el = alineas[i]
        var oSize = window.getComputedStyle(el, null).getPropertyValue('font-size');
        var nSize = Number(oSize.replace("px",""))+num;
        el.style.fontSize = nSize+"px"
    }
}

Call it like fontSize(5) or fontSize(-5) to go up 5 pixels or down 5 pixels respectively.

JSFiddle

Altri suggerimenti

Use parseInt to get your current size, then simply increase it by the amount you want.

var sizeChange = 2; // To increase font size by 2px
var size = parseInt(alineas[alinea].style.fontSize); // "12px" -> 12 
size += sizeChange; // 14
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top