Home > Article > Web Front-end > How to change CSS styles using JQuery
JQuery is an excellent JavaScript library that simplifies JavaScript code writing. There is a $.css() method in jQuery that can be used to change CSS styles. In this article, we will discuss how to change CSS styles using JQuery.
It is very easy to change CSS styles using JQuery. You just need to call the ".css()" method after the selector and provide an object through the method to change the CSS properties. For example:
$("p").css("color", "red");
The above code will change the color of all paragraph text to red. This is the most basic way to change CSS styles in JQuery.
Using the $.css() method can also change multiple attributes at the same time. The following example changes the color and font size of text:
$("p").css({ "color": "red", "font-size": "20px" });
You can pass variable values to the $.css() method to dynamically change the CSS properties of an element. For example:
var color = "red"; $("p").css("color", color);
JQuery can also use the toggleClass() method to change the CSS class. If you specify two CSS classes in one of the method calls, it will automatically switch between the two classes. For example:
$("p").toggleClass("red");
The above code will switch the red background of all paragraph elements.
JQuery can use the .animate() method to animate CSS style changes. Here is an example using .animate():
$("p").animate({ "font-size": "30px", "opacity": "0.5" }, 1000);
The above code will slowly change the font size of all paragraph elements to 30px and change the opacity to 0.5.
In this article, we have learned about the different ways JQuery can change CSS styles. By using JQuery, changing the CSS properties of an element has become much easier and simpler. I hope this article can help you gain a better grasp of JQuery.
The above is the detailed content of How to change CSS styles using JQuery. For more information, please follow other related articles on the PHP Chinese website!