Category:javascript
Article From:https://www.cnblogs.com/nulifendou/p/9126408.html

In the actual application of the web, it is necessary to change the CSS style of the element according to the different conditions. This function can be realized by adding a CSS class to the element dynamically.

1. Add and delete a CSS class using addClass () and removeClass ().

The code example is as follows:

<!DOCTYPE html>
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>Ant tribe</title> 
<style type="text/css">
.mytest{
  border:1px solid green;
  width:100px;
  height:100px;
  color:red;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
  $("#add").click(function () {
    $("div").addClass("mytest");
  });
  $("#del").click(function () {
    $("div").removeClass("mytest");
  })
})
</script>
<body>
<div>Cherish the present, because only the present is real.</div>
<button id="add">Add style</button>
<button id="del">Deleting style</button>
</body>
</html>

The above code can add and delete the specified style. The above is just a demo, which can be added or deleted according to the specific needs.

Two. Use toggleClass () to toggle the addition and deletion of style classes:

If the matching object has a specified style class, then toggleClass () can delete the specified class, and if not, the specified class will be added.

The code strength is as follows:

<!DOCTYPE html>
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>Ant tribe</title> 
<style type="text/css">
.mytest{
  border:1px solid green;
  width:100px;
  height:100px;
  color:red;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
  $("#switch").click(function () {
    $("div").toggleClass("mytest");
  });
})
</script>
<body>
<div class="mytest">Cherish the present, because only the present is real.</div>
<button id="switch">Delete and add handoff</button>
</body>
</html>

The above code can toggle the deletion and addition of the specified style class.

 Reprint address: jQuery how to add and delete a style for a specified tag.

Design knowledge: jQuery tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *