The simple jQuery method toggleClass is used to realize interlaced color change

  • 2020-03-30 04:10:57
  • OfStack

Today, toggleClass() implements interlaced color change in a concise way: the code is as follows:


<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> Interlaced color change </title>
<script src="js/jquery-1.4.2.min.js"></script>
<style type="text/css">
body,table,td, {
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
.h {
background:#f3f3f3;
color:#000;
}
.c {
background:#ebebeb;
color:#000;
}
</style>
</head>

<body>
<div id="aaa">
<form>
<table id="table" width="50%" border="0" cellpadding="3" cellspacing="1">
<tr>
<td width="30" align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td>
<td> Maple front end </td>
<td> Maple front end </td>
</tr>
<tr>
<td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td>
<td> Maple front end </td>
<td> Maple front end </td>
</tr>
<tr>
<td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td>
<td> Maple front end </td>
<td> Maple front end </td>
</tr>
<tr>
<td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td>
<td> Maple front end </td>
<td> Maple front end </td>
</tr>
<tr>
<td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td>
<td> Maple front end </td>
<td> Maple front end </td>
</tr>
<tr>
<td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td>
<td> Maple front end </td>
<td> Maple front end </td>
</tr>
<tr>
<td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td>
<td> Maple front end </td>
<td> Maple front end </td>
</tr>
</table>
</form>
</div>
<script>

The first is more complex:


$(function()
{
$("#table tr").hover(function()
{
$(this).addClass("h");
},function()
{
$(this).removeClass("h");
})
$("input").click(function()
{
if($(this).attr("checked"))
{
$(this).closest("tr").addClass("c");
}
else
{
$(this).closest("tr").removeClass("c");
}
})
})

The second is simpler:

ToggleClass () toggles one or more classes that set or remove the selected element.

This method checks the class specified in each element. Add the class if it does not exist and remove it if it is set. This is called the toggle effect.

However, by using the "switch" parameter, you can specify that only classes are deleted or only added.


$(function(){
$("#table tr").hover(function(){
$(this).toggleClass("h");
})

$("input").click(function(){
var d = $(this);
d.closest('tr').toggleClass("c",d.attr("checked")) ;
})
})
</script>
</body>
</html>

Related articles: