JqueryUI - toggleClass() 切换类方法
本章将讨论toggleClass() 方法,这是一个有用的新操作类。 toggleClass() 方法为匹配元素集中的每个元素添加或删除一个或多个类。
语法
在 jQueryUI 1.0 版本中添加
toggleClass() 方法的基本语法如下 −
.toggleClass( className [, switch ] [, duration ] [, easing ] [, complete ] )
| 序号 | 参数 & 说明日> |
|---|---|
| 1 | className 这是一个字符串,表示要添加、删除或切换的 CSS 类名或以空格分隔的类名列表。 |
| 2 | switch 这是布尔类型,如果指定,则强制 toggleClass() 方法在 true 时添加类,或者在 false 时删除类 . |
| 3 | duration 这是 Number 或 String 类型,可以选择提供 slow、normal、fast 之一, 或以毫秒为单位的效果持续时间。 如果省略,则 animate() 方法确定默认值。 它的默认值为 400。 |
| 4 | easing 要传递给 animate() 方法的缓动函数的名称。 |
| 5 | complete 这是每个元素在效果完成时调用的回调方法。 |
在 jQueryUI 1.9 版本中添加
在 1.9 版本中,此方法现在支持 children 选项,该选项还将为后代元素设置动画。
.toggleClass( className [, switch ] [, options ] )
| 序号 | 参数 & 说明日> |
|---|---|
| 1 | className 这是一个字符串,表示要添加、删除或切换的 CSS 类名或以空格分隔的类名列表。 |
| 2 | switch 这是布尔类型,如果指定,则强制 toggleClass() 方法在 true 时添加类,或者在 false 时删除类 . |
| 3 | options 这代表所有动画设置。 所有属性都是可选的。 可能的值是 −
|
示例
以下示例演示了 toggleClass() 方法的使用。
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Switch Class Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style>
.class1 {
border-width : 10px;
border-color : grey;
background-color : #cedc98;
color : black;
}
</style>
<script>
function toggle () {
$("#para").toggleClass ("class1", 1000);
}
</script>
</head>
<body>
<button onclick = toggle()> Toggle </button>
<p id = "para" style = border-style:solid> Welcome to Tutorials Point </p>
</body>
</html>
让我们将上面的代码保存在一个 HTML 文件 toggleclassexample.asp 中,并在支持 javascript 的标准浏览器中打开它,您还必须看到以下输出。 现在,您可以使用结果 −
单击 Toggle 切换按钮以查看文本的 CSS 类是如何更改的。

