Home > Article > Web Front-end > How to change font size in javascript
In JavaScript, you can use the fontSize property of the Style object to change the font size. This property can set the font size of the text. The syntax format is "element object.style.fontSize="value"".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In javascript, you can use the fontSize property of the Style object to change the font size.
Let’s take an example to see how the fontSize attribute changes the font size.
First of all, let’s look at the layout, write a simple sentence and two buttons:
<input id="Btn1" type="button" value="+" name=""/> <input id="Btn2" type="button" value="-" name=""/> <p id="p1" style="font-size:14px;">这是一些文字这是一些文字这是一些文字这是一些文字</p>
The rendering is as follows:
Then , you need to control the size of the text by clicking the plus and minus buttons. The js code is as follows:
<script> window.onload= function(){ var oPtxt=document.getElementById("p1"); var oBtn1=document.getElementById("Btn1"); var oBtn2=document.getElementById("Btn2"); var num = 14; /*定义一个初始变量*/ oBtn1.onclick = function(){ num++; oPtxt.style.fontSize=num+'px'; }; oBtn2.onclick = function(){ num--; oPtxt.style.fontSize=num+'px'; } } </script>
Click the " " button once, and the text will increase by one pixel. If you keep clicking, it will keep getting bigger:
Click the "-" button once, and the text will be reduced by one pixel. If you keep clicking, it will continue to become smaller:
It’s that simple. Be sure to note that when defining the initial variable, it must be a global variable. If you need to operate the button to make the text change, then the increase and decrease of the variable must be a local variable.
[Related recommendations: javascript learning tutorial]
Description: HTML DOM Style fontSize attribute
## The #fontSize property sets or returns the font size of text. Syntax:object.style.fontSize
object.style.fontSize = "value"Attribute value:
Description | |
---|---|
|
smaller |
larger | |
length | |
% | |
The above is the detailed content of How to change font size in javascript. For more information, please follow other related articles on the PHP Chinese website!