jQuery provides three methods to change the style of page elements. Although they are similar to traditional methods, they save a lot of code.
We often use Javascript to change The style of the page element. One way is to change the CSS class(Class) of the page element. In traditional Javascript, we usually do this by processing the classname attribute of HTML Dom; while jQuery Three methods are provided to implement this function. Although they are similar to the traditional methods, they save a lot of code. Still the same sentence - "jQuery makes JavaScript code concise!"
1. addClass() - Add CSS class
$("#target").addClass("newClass");
//#target refers to the ID of the element that needs to be styled
//newClass refers to the name of the CSS class
2. removeClass() - removes the CSS class
$("#target" ).removeClass("oldClass");
//#target refers to the ID of the element whose CSS class needs to be removed
//oldClass refers to the name of the CSS class
3. toggleClass() - Add or remove a CSS class: If the CSS class already exists, it will be removed; conversely, if the CSS class does not exist, it will be added.
$("#target").toggleClass("newClass")
//If the element with ID "target" has defined CSS style, it will be removed;
//On the contrary, CSS The class "newClass" will be assigned this ID.
In actual application, we often define these CSS classes first, and then change the page element style through Javascript event triggering (such as clicking a link). In addition, jQuery also provides a method hasClass("className") to determine whether an element has been assigned a CSS class.
The following is a complete example.
The code is as follows:
<!DOCTYPE HTML> <head> <title>图片闪烁</title> <style type="text/css"> @-webkit-keyframes twinkling{ /*透明度由0到1*/ 0%{ opacity:0; /*透明度为0*/ } 100%{ opacity:1; /*透明度为1*/ } } .up{ -webkit-animation: twinkling 1s infinite ease-in-out; } </style> </head> <body> <p id="soccer" class="up"> 哈哈 </p> <br/> <input type="button" onclick='btnClick()'> <script src="./jQuery/jquery-1.8.3.js" type="text/javascript"></script> <script> function btnClick(){ //$("#soccer").removeClass("up"); $("#soccer").toggleClass("up"); //$("p:first").removeClass("intro"); } </script> </body> </html>
The above is the detailed content of Detailed explanation of three methods of jQuery operating element css style. For more information, please follow other related articles on the PHP Chinese website!