如何支持“背景颜色”
animate方法,能够支持单位为数值(px、em、%)的CSS属性,对于背景颜色的变化,animate是不支持的。但是我们有时也希望颜色能够发生变化,此时,我们可以使用一个jQuery插件——jQuery.Color()。点击此处可下载——jQuery.Color插件(访问密码:236d)
-
<!doctype html>
-
<html>
-
<head>
-
<meta charset="UTF-8">
-
<title>HTML5学堂 - jQuery animate</title>
-
<link rel="stylesheet" href="model/css/reset.css">
-
<script src="model/js/jquery-1.11.2.js"></script>
-
<script src="model/js/jquery.color.js"></script>
-
<style>
-
.btn {
-
height: 50px;
-
line-height: 50px;
-
font-size: 32px;
-
}
-
.wrap {
-
width: 400px;
-
height: 50px;
-
background: #39f;
-
color: #fff;
-
font-size: 32px;
-
font-weight: bold;
-
text-align: center;
-
line-height: 50px;
-
}
-
</style>
-
</head>
-
<body>
-
<div class="btn">点击此处</div>
-
<div class="wrap">HTML5学堂</div>
-
<script>
-
$(".btn").click(function(){
-
$(".wrap").animate({
-
"background-color" : "#999"
-
}, 1000)
-
});
-
</script>
-
</body>
-
</html>
animate动画中的变量应用
jQuery的动画属性animate,除了能够设置基本的数值之外,还可以设置相对的值。如果一个值提供了一个+=和 -=操作符号,那么目标值 = 当前的值 + 或 - 给定的值。
代码示例:
-
<!doctype html>
-
<html>
-
<head>
-
<meta charset="UTF-8">
-
<title>HTML5学堂 - jQuery animate</title>
-
<link rel="stylesheet" href="model/css/reset.css">
-
<script src="model/js/jquery-1.11.2.js"></script>
-
<style>
-
.btn {
-
height: 50px;
-
line-height: 50px;
-
font-size: 32px;
-
}
-
.wrap {
-
width: 400px;
-
height: 50px;
-
background: #39f;
-
color: #fff;
-
font-size: 32px;
-
font-weight: bold;
-
text-align: center;
-
line-height: 50px;
-
}
-
</style>
-
</head>
-
<body>
-
<div class="btn">点击此处</div>
-
<div class="wrap">HTML5学堂</div>
-
<script>
-
$(".btn").click(function(){
-
$(".wrap").animate({
-
"width" : "+=100px"
-
}, 1000)
-
});
-
</script>
-
</body>
-
</html>
animate动画中的特殊属性值
jQuery的animate方法当中,对于属性的属性值设置,除了使用数值之外,还可以考虑“show”、“hide”、“toggle”。个人认为,这三种方法的优势在于,对于需要隐藏或显示此类的特效,能够具备较好的扩展性。换句话说,对于一个元素,如果初始状态是宽度400像素,希望能够点击之后宽度变化为0,再点击某处宽度恢复。我们可以使用animate({"width" : "0px"});和animate({"width" : "400px"});来处理。但是,如果此时当前元素的初始宽度并不是400,而是600像素,那么上面这段代码就变得没有“扩展性”了。虽然我们的确可以使用变量替换掉常量,再使用.css()方法获取当前元素的样式,但是也可以通过上面提到的“toggle”等特殊属性值进行控制。
-
<!doctype html>
-
<html>
-
<head>
-
<meta charset="UTF-8">
-
<title>HTML5学堂 - jQuery animate</title>
-
<link rel="stylesheet" href="model/css/reset.css">
-
<script src="model/js/jquery-1.11.2.js"></script>
-
<style>
-
.btn {
-
height: 50px;
-
line-height: 50px;
-
font-size: 32px;
-
}
-
.wrap {
-
width: 400px;
-
height: 50px;
-
background: #39f;
-
color: #fff;
-
font-size: 32px;
-
font-weight: bold;
-
text-align: center;
-
line-height: 50px;
-
}
-
</style>
-
</head>
-
<body>
-
<div class="btn">点击此处</div>
-
<div class="wrap">HTML5学堂</div>
-
<script>
-
$(".btn").click(function(){
-
$(".wrap").animate({
-
"width" : "toggle"
-
}, 1000)
-
});
-
</script>
-
</body>
-
</html>
链式动画
我们能够使用animate实现多个动画,但是如何让一个一个的动画有顺序的执行呢?此处会使用到queue这个属性设置。queue表示是否在效果队列中放置动画(即,是否形成一个链式动画)。如果queue的值为false,则动画立即开始,如果为queue的值设置为true,则表示是链式动画。默认为true(链式)。
个人认为,并没有太大的必要,因为默认的就是链式动画,如果希望同时变化,完全可以写在一个animate当中。