通过animate方法可以设置元素某属性值上的动画,可以设置一个或多个属性值,动画执行完成后会执行一个函数。
$('#div1').animate({
width:300,
height:300
},1000,swing,function(){
alert('done!');
});
参数可以写成数字表达式:
$('#div1').animate({
width:'+=100',
height:300
},1000,swing,function(){
alert('done!');
});
jQuery 动画 - animate() 方法
jQuery animate() 方法用于创建自定义动画。
语法:
$(selector).animate({params},speed,callback);
必需的 params 参数定义形成动画的 CSS 属性。
可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
可选的 callback 参数是动画完成后所执行的函数名称。
下面的例子演示 animate() 方法的简单应用。它把 <div> 元素往右边移动了 250 像素:
实例
$("button").click(function(){ $("div").animate({left:'250px'});});
jQuery animate() - 操作多个属性
请注意,生成动画的过程中可同时使用多个属性:
实例
$("button").click(function(){ $("div").animate({ left:'250px',
opacity:'0.5',
height:'150px',
width:'150px' });});
jQuery animate() - 使用相对值
也可以定义相对值(该值相对于元素的当前值)。需要在值的前面加上 += 或 -=:
实例
$("button").click(function(){ $("div").animate({ left:'250px',
height:'+=150px',
width:'+=150px' });});
jQuery animate() - 使用预定义的值
您甚至可以把属性的动画值设置为 "show"、"hide" 或 "toggle":
实例
$("button").click(function(){ $("div").animate({ height:'toggle' });});
jQuery animate() - 使用队列功能
默认地,jQuery 提供针对动画的队列功能。
这意味着如果您在彼此之后编写多个 animate() 调用,jQuery 会创建包含这些方法调用的"内部"队列。然后逐一运行这些 animate 调用。
实例 1
$("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");});
下面的例子把 <div> 元素往右边移动了 100 像素,然后增加文本的字号:
实例 2
$("button").click(function(){ var div=$("div");
div.animate({left:'100px'},"slow");
div.animate({fontSize:'3em'},"slow");});