JQuery three ways to manipulate CSS styles for elements

  • 2020-03-30 03:11:29
  • OfStack

We often use Javascript to change the style of page elements. One way to do this is to change the CSS Class of a page element, which in traditional Javascript is usually done by working with the classname feature of the HTML Dom. There are three ways to do this in jQuery that are similar to traditional methods but save a lot of code. Again, "jQuery makes JavaScript code simple!"

1. AddClass () - add a CSS class
$(" # target "). The 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 CSS classes
$(" # target "). RemoveClass (" oldClass ");
//#target refers to the ID of the element that needs to be removed from the CSS class
//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 the ID of "target" has a CSS style already defined, it will be removed;
// instead, the CSS class "newClass" will be assigned to the ID.

In practice, we often define these CSS classes and then change the style of a page element via Javascript events, such as clicking on a link. In addition, jQuery provides a method called hasClass (" className ") to determine whether an element has been assigned to a CSS class.

Here is a complete example.
 
<!DOCTYPE HTML> 
<head> 
<title> Images flashing </title> 
<style type="text/css"> 

@-webkit-keyframes twinkling{  
0%{ 
opacity:0;  
} 
100%{ 
opacity: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> 

Related articles: