Home > Web Front-end > JS Tutorial > body text

Code to control font size through JavaScript_javascript tips

WBOY
Release: 2016-05-16 18:01:19
Original
1204 people have browsed it

In order to add this code to your web page you must use pixel sized fonts (px), not relative sized fonts, use "em" or "%". Of course if you use other font units the code can be easily adapted to these. If the script cannot find the font size for a paragraph, it will default to 12px.
Core code:

Copy code The code is as follows:

var min=8;
var max=18;
function increaseFontSize() {
var p = document.getElementsByTagName('p');
for(i=0;i if(p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px",""));
} else {
var s = 12;
}
if(s!=max) {
s = 1;
}
p[i].style.fontSize = s "px"
}
}
function decreaseFontSize() {
var p = document.getElementsByTagName('p');
for(i=0;i if (p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px",""));
} else {
var s = 12;
}
if(s!=min) {
s -= 1;
}
p[i].style.fontSize = s "px"
}
}

Include the above code in your web page (either place it in the header section, or place it in an external JS file and import it). You can then call functions that increase and decrease font size like below.
Usage:
Copy code The code is as follows:
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template