jQuerytoggleClass()以这样一种方式添加或删除所选元素中的一个或多个类,即如果所选元素已经具有该类,则将其删除;否则,jQuery将其删除。如果元素没有类,则添加该元素,即切换类。
例试试这个代码»
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery toggleClass() Demo</title>
<style>
p{
padding: 10px;
cursor: pointer;
font: bold 16px sans-serif;
}
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).toggleClass("highlight");
});
});
</script>
</head>
<body>
<p>Click on me to toggle highlighting.</p>
<p class="highlight">Click on me to toggle highlighting.</p>
<p>Click on me to toggle highlighting.</p>
</body>
</html>
如果您觉得本文的内容对您的学习有所帮助:
关键字:
jQuery