JqueryUI - addClass() 方法
本章将讨论 addClass() 方法,这是用于管理 jQueryUI 视觉效果的方法之一。 addClass() 方法允许对 CSS 属性的更改进行动画处理。
addClass() 方法将指定的类添加到匹配的元素,同时为所有样式更改设置动画。
语法
在 jQueryUI 1.0 版本中添加
addClass() 方法的基本语法如下 −
.addClass( className [, duration ] [, easing ] [, complete ] )
| 序号 | 参数 & 说明日> |
|---|---|
| 1 | className 这是一个包含一个或多个 CSS 类(以空格分隔)的字符串。 |
| 2 | duration 这是 Number 或 String 类型,表示效果的毫秒数。 值 0 直接采用新样式中的元素,没有进展。 它的默认值为 400。 |
| 3 | easing 这是 String 类型,指示效果的进展方式。 它的默认值是swing。 可能的值在此处。 |
| 4 | complete 这是当每个元素的效果完成时为每个元素调用的回调方法。 |
在 jQueryUI 1.9 版本中添加
在 1.9 版本中,此方法现在支持 children 选项,该选项还将为后代元素设置动画。
.addClass( className [, options ] )
| 序号 | 参数 & 说明日> |
|---|---|
| 1 | className 这是一个包含一个或多个 CSS 类(以空格分隔)的字符串。 |
| 2 | options 这代表所有动画设置。 所有属性都是可选的。 可能的值是 −
|
示例
以下示例演示了 addClass() 方法的使用。
传递单个类
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery UI addClass 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>
<style>
.elemClass {
width: 200px;
height: 50px;
background-color: #b9cd6d;
}
.myClass {
font-size: 40px; background-color: #ccc; color: white;
}
</style>
<script type = "text/javascript">
$(document).ready(function() {
$('.button').click(function() {
if (this.id == "add") {
$('#animTarget').addClass("myClass", "fast")
} else {
$('#animTarget').removeClass("myClass", "fast")
}
})
});
</script>
</head>
<body>
<div id = animTarget class = "elemClass">
Hello!
</div>
<button class = "button" id = "add">Add Class</button>
<button class = "button" id = "remove">Remove Class</button>
</body>
</html>
让我们将上面的代码保存在一个 HTML 文件 addclassexample.htm 中,并在支持 javascript 的标准浏览器中打开它,您还须看到以下输出。 现在,您可以查看结果 −
单击Add ClassRemove Class 和删除类 删除类按钮以查看类对框的影响。
传递多个类
此示例说明如何将多个类传递给 addClass 方法。
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI addClass 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>
.red { color: red; }
.big { font-size: 5em; }
.spaced { padding: 1em; }
</style>
<script>
$(document).ready(function() {
$('.button-1').click(function() {
$( "#welcome" ).addClass( "red big spaced", 3000 );
});
});
</script>
</head>
<body>
<p id = "welcome">Welcome to Tutorials Point!</p>
<button class = "button-1">Click me</button>
</body>
</html>
让我们将上面的代码保存在一个 HTML 文件 addclassexample.htm 中,并在支持 javascript 的标准浏览器中打开它,您还必须看到以下输出。 现在,您可以查看结果 −

