JQuery is a popular JavaScript library that makes it easier for developers to manipulate HTML documents, handle events, create animations, and perform common tasks such as AJAX. Among them, CSS operation is one of the functions frequently used by developers.
When using JQuery to set CSS, developers can use the following two methods:
.css() method to set or Returns one or more style properties of the specified element. This method has two uses:
// 设置单个属性 $(selector).css(property, value) // 设置多个属性 $(selector).css({property1: value1, property2: value2, ...})
Among them, selector
is the element selector to set the CSS property, property
is the name of the CSS property to be set, value
is the CSS property value to be set. In the second usage, multiple CSS properties can be set at the same time, each property being represented in the form of a key-value pair.
For example, to set the background color of the element with ID myDiv
to red and the font color to white, you can use the following code:
$("#myDiv").css("background-color", "red"); $("#myDiv").css("color", "white");
or:
$("#myDiv").css({"background-color": "red", "color": "white"});
The .addClass() method can add one or more style classes to the specified element, while the .removeClass() method can remove it from the specified element. Remove one or more style classes. The syntax format of these two methods is as follows:
// 添加一个样式类 $(selector).addClass(classname) // 删除一个样式类 $(selector).removeClass(classname)
where classname
is the name of the style class to be added/removed.
For example, to add two style classes named bg-red
and text-white
to the element with ID myDiv
, you can Use the following code:
$("#myDiv").addClass("bg-red"); $("#myDiv").addClass("text-white");
To delete multiple style classes, you can also use commas to separate multiple class names:
$("#myDiv").removeClass("bg-red, text-white");
The above two methods can be flexibly applied according to the needs of developers. Achieve the purpose of quickly setting and controlling page styles.
In actual project development, due to the high complexity of styles, it is recommended to encapsulate CSS styles into independent style sheets as much as possible, and add/delete class names in JQuery to achieve style setting and control. This not only makes the style sheet easier to manage, but also allows you to reuse styles among multiple elements, improve code reusability, reduce the amount of code, and reduce maintenance costs.
The above is the detailed content of How to set css in jquery. For more information, please follow other related articles on the PHP Chinese website!