How to adjust font size in javascript

WBOY
Release: 2023-05-09 12:28:37
Original
4386 people have browsed it

JavaScript is a widely used programming language that can be used to implement various interactive effects and functions in web pages. Among them, adjusting font size is a common operation on web pages. This article will introduce how JavaScript adjusts the size of text in web pages.

1. Use DOM operations to adjust font size

DOM (Document Object Model) is an important part of JavaScript and is used to manipulate the content in web pages. Through the DOM, we can easily find the element whose font size needs to be modified, and then adjust its size using the .style.fontSize property.

First, we need to find the element that needs to be resized. The element object that needs to be modified can be obtained by id or class, for example:

<p id="paragraph">这是一个段落</p>
<p class="text">这是另一个段落</p>
Copy after login

Through the getElementById method and getElementsByClassName method in JavaScript, we can obtain these two element objects:

var p1 = document.getElementById("paragraph"); //获取id为paragraph的元素对象
var p2 = document.getElementsByClassName("text")[0]; //获取class为text的元素对象数组,取出第一个元素
Copy after login

Next, we can modify the font size through the .style.fontSize property:

p1.style.fontSize = "20px"; //将id为paragraph的元素的字体大小设置为20px
p2.style.fontSize = "16px"; //将class为text的元素的字体大小设置为16px
Copy after login

This way we can easily adjust the font size.

2. Use jQuery library to adjust font size

jQuery is a popular JavaScript library that simplifies the steps of various operations and makes JavaScript programming easier and more concise. Using the jQuery library to adjust font size reduces the amount of code and is cross-browser compatible.

Before using the jQuery library, you need to introduce the jQuery library into the web page:

<script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js"></script>
Copy after login

Then, we can use the selector in jQuery to get the elements that need to modify the font size, as shown below :

$("#paragraph").css("font-size","20px"); //将id为paragraph的元素的字体大小设置为20px
$(".text").css("font-size","16px"); //将class为text的元素的字体大小设置为16px
Copy after login

Using the jQuery library, you can not only use the .css method to modify the font size, but also use the .animate method to achieve more gorgeous animation effects. For example:

$("#paragraph").animate({fontSize: "20px"}, 1000); //用1000毫秒的时间将id为paragraph的元素的字体大小调整为20px
$(".text").animate({fontSize: "16px"}, 1000); //用1000毫秒的时间将class为text的元素的字体大小调整为16px
Copy after login

3. Use CSS to control font size

In addition to using JavaScript to control font size, you can also use CSS styles to adjust font size. You can easily adjust the size of text in a web page by setting the font-size attribute in the