jQuery manipulates CSS
Modify CSS style
To modify the style of an element, we can modify the element CSS class or directly modify the element's style.
An element can apply multiple css classes, but unfortunately in the DOM attribute, it is stored as a space-separated string instead of an array. So if we wanted to add or delete multiple attributes to an element in the original JavaScript era, we had to operate the string ourselves.
jQuery makes it incredibly easy.
1. Modify CSS classes
The following table is the jQuery methods related to modifying CSS classes:
Use With the above method, we can modify the CSS class of the element like a collection, and we no longer have to manually parse strings.
Note that the parameters of addClass(class) and removeClass(classes) can be passed in multiple css classes at one time, separated by spaces, for example:
$("#btnAdd").bind(" click", function(event) {
$("p").addClass("colorRed borderBlue");
});
removeClass method parameters are optional, if not Pass in parameters to remove all CSS classes:
$("p").removeClass();
2. Modify CSS style
Similarly, when we want to modify a specific CSS style of an element, that is, modify the element attribute "style", jQuery also provides the corresponding method:
<!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>使用jQ控制CSS</title> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> <style type="text/css"> .w1{font-size: 14px;} .w2{font-size: 20px; } </style> </head> <body> <ul> <li class="w1"><a href="#">公司简介</a> </li> <li class="w1"><a href="#">公司文化</a> </li> <li class="w1"><a href="#">发展战略</a> </li> <li class="w1"><a href="#">公司简介</a> </li> </ul> </body> <script type="text/javascript"> $(function () { $( ".w1").click(function () { $(this).removeClass("w1"); $(this).addClass("w2"); $(this).siblings().removeClass("w2"); $(this).siblings().addClass("w1"); }); }); </script> </html>