1. jQuery animate()方法
1.1. animate()方法执行CSS属性集的自定义动画。
1.2. 该方法通过CSS样式将元素从一个状态改变为另一个状态。CSS属性值是逐渐改变的, 这样就可以创建动画效果。
1.3. 只有数字值可创建动画(比如: "margin:30px")。字符串值无法创建动画(比如: "background-color:red")。
1.4. 语法1:
$(selector).animate(styles,speed,easing,callback);
1.5. 参数
1.6. 语法2:
$(selector).animate(styles,options);
1.7. 参数
2. jQuery animate()操作多个属性
2.1. 请注意, 生成动画的过程中可同时使用多个属性:
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
2.2. animate()方法几乎可以操作所有的CSS属性。不过, 需要记住一件重要的事情: 当使用animate()时, 必须使用Camel标记法书写所有的属性名, 比如: 必须使用paddingLeft而不是padding-left; 使用marginRight 而不是margin-right等等。
2.3. 同时, 色彩动画并不包含在核心jQuery库中。
2.4. 如果需要生成颜色动画, 您需要从jQuery.com下载Color Animations插件。
3. jQuery animate()使用相对值
3.1. 也可以定义相对值(该值相对于元素的当前值)。需要在值的前面加上+=或-=:
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=150px',
width: '+=150px'
});
});
4. jQuery animate()使用预定义的值
4.1. 您甚至可以把属性的动画值设置为"show"、"hide"或"toggle":
$("button").click(function(){
$("div").animate({
height:'toggle'
});
});
5. jQuery animate()使用队列功能
5.1. 默认地, jQuery提供针对动画的队列功能。
5.2. 这意味着如果您在彼此之后编写多个animate()调用, jQuery会创建包含这些方法调用的"内部"队列。然后逐一运行这些animate调用。
5.3. 如果您希望在彼此之后执行不同的动画, 那么我们要利用队列功能:
$("button").click(function(){
var div=$("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "slow");
});
6. 例子
6.1. 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery动画</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#btn1').click(function(){
$("div:visible").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '500px'
}, "slow", "swing");
});
$('#btn2').click(function(){
$("div:visible").animate({
left: '+=250px',
opacity: '+=0.5',
height: '+=150px',
width: '+=500px'
}, "normal", "swing");
});
$('#btn3').click(function(){
$("div").animate({
height: 'toggle'
}, "fast", "swing");
});
$('#btn4').click(function(){
var div = $("div:visible");
// 使用$(selector).animate(styles,options);语法, callback函数无效
div.animate({height:'+=100px', opacity: '0.5'}, {speed: 3000, easing: "linear"});
div.animate({width:'+=100px', opacity: '0'}, {speed: 1000, easing: "linear"});
div.animate({height:'+=100px', opacity: '0.5'}, {speed: 4000, easing: "linear"});
div.animate({letterSpacing:'+=10px'}, {speed: 1000, easing: "linear", step: function(){
console.log('动画的每完成一步都会执行该函数');
}, queue: true});
});
});
</script>
</head>
<body>
<button id="btn1">animate操作多个属性</button> <button id="btn2">animate使用相对值</button>
<button id="btn3">animate使用预定义的值</button> <button id="btn4">animate使用队列功能</button><br /><br />
<div style="background-color: red; width:400px; height: 50px; position: relative;">jQuery animate()方法允许您创建自定义的动画。</div>
</body>
</html>
6.2. 效果图