addClass()和removeClass()分别只能添加和者移除className,但是这个toggleClass()方法却不同,如果元素有这个类名,它将补移除;反之,如果元素没有这个类名,那么将加上这个类名。
<!DOCTYPE html>
<html>
<head>
<style>
ul { margin-left:20px; color:blue; }
li { cursor:default; }
li.active { background:black;color:white; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<ul>
<li>Milk</li>
<li>White</li>
<li>Carrots</li>
<li>Orange</li>
<li>Broccoli</li>
<li>Green</li>
</ul>
<script>
$("li")
.filter(":odd") //隐藏偶数行的<li>元素
.hide()
.end() //结束操作,返回指向上一级的<li>元素
.filter(":even") //对奇数行进行操作
.hover(
function () {
$(this).toggleClass("active") //添加或者删除这个类active
.next().stop(true, true).slideToggle(); //.stop()即停止当前的hide()动作,滚动显示出来
}
);
</script>
</body>
</html>