JQuery operates on the css style of the element

  • 2020-05-12 02:09:21
  • OfStack

We often use Javascript to change the style of page elements. One way is to change the page element

The CSS class (Class), which in traditional Javascript, we usually deal with by HTML

Dom's classname feature; There are three ways to do this in jQuery,

Although they share the same ideas as traditional methods, they save a lot of code. Still that sentence

"jQuery makes JavaScript code simple!"

1. Add CSS class to addClass()


$( " #target " ).addClass( " newClass " );
//#target Refers to the element that needs to be styled ID
//newClass Refers to the CSS The name of the class

2. removeClass(), remove the CSS class


$( " #target " ).removeClass( " oldClass " );
//#target That means it needs to be removed CSS Of an element of a class ID
//oldClass Refers to the CSS The name of the class

3. toggleClass() adds or removes the 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 ID As a" target "Is already defined CSS Style, it will be removed;
// On the other hand, CSS Class" newClass "Shall be assigned to the ID .

In practice, we often define these CSS classes and then touch them through the Javascript event

Post (such as clicking a link) to change the style of a page element. In addition, jQuery also offers one square

The hasClass(" className ") method is used to determine whether an element has been assigned to an CSS class.

Here is a complete example.


 <span style= " font-size:18px; " ><!DOCTYPE HTML> 
     <head> 
     <title> Images flashing </title> 
     <style type= " text/css " > 
     @-webkit-keyframes twinkling{   /* Transparency by 0 to 1*/ 
         0%{ 
             opacity:0;              /* Opacity to 0*/ 
         } 
         100%{ 
             opacity:1;              /* Opacity to 1*/ 
         } 
     } 
     .up{ 
         -webkit-animation: twinkling 1s infinite ease-in-out; 
     } 
     </style> 
     </head> 
     <body> 
     <div id= " soccer " class= " up " > 
     Ha ha  
     </div> 
     <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>
 </span>

That's all I have to say about jQuery operation CSS style in this article. I hope you enjoy it.


Related articles: