Home  >  Article  >  Web Front-end  >  How to change CSS styles using JQuery

How to change CSS styles using JQuery

PHPz
PHPzOriginal
2023-04-06 14:50:50964browse

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.

1. jQuery .css() method

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.

2. Change multiple attributes

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"
});

3. Using variables

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);

4. Switch class

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.

5. Animation

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!

Statement:
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