JQuery is one of the most popular JavaScript libraries currently, which allows developers to operate HTML pages more easily. One of the most basic and commonly used functions is to use JQuery to change CSS styles.
1. Basic syntax for changing CSS styles with JQuery
In JQuery, we use the .css() method to change the css style of elements. The syntax is as follows:
$(selector).css(property,value)
where , selector is the element that needs to be changed, property is the CSS attribute to be changed, and value is the new value of the attribute. For example, we can change the background color of the element to red:
$("#myDiv").css("background-color", "red");
2. How to change the CSS style with JQuery
We can directly set the value of the CSS property to the new value through the .css() method. For example, set the font color to blue:
$("#myDiv").css("color", "blue");
Note: The css() method will only change the inline style of the specified element (that is, the style written in the element tag), and will not affect the external style sheet the rule of.
We can use the .addClass() method to add a CSS class to an element and the .removeClass() method to remove a CSS class. The following example demonstrates how to click a button to switch the class of a div:
$("#btnToggle").click(function(){ $("#myDiv").toggleClass("active"); });
The .toggleClass() method will add or delete the specified class name.
We can set multiple CSS properties and values at once, just pass in an object in the .css() method . For example, set border, width, height, and padding to the same value at the same time:
$("#myDiv").css({ "border": "1px solid #000", "width": "50px", "height": "50px", "padding": "10px" });
We can use the .css() method to get it Specifies the CSS property value of the element. For example, get the background color of an element:
var backgroundColor = $("#myDiv").css("background-color");
Through the .css() method, we can flexibly change and obtain the CSS style of page elements to achieve richer user interaction effects.
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!