animate(params,[speed],[easing],[fn])
概述
用于创建自定义动画的函数。
这个函数的关键在于指定动画形式及结果样式属性对象。这个对象中每个属性都表示一个可以变化的样式属性(如“height”、“top”或“opacity”)。注意:所有指定的属性必须用骆驼形式,比如用marginLeft代替margin-left.而每个属性的值表示这个样式属性到多少时动画结束。如果是一个数值,样式属性就会从当前的值渐变到指定的值。如果使用的是“hide”、“show”或“toggle”这样的字符串值,则会为该属性调用默认的动画形式。
在 jQuery 1.2 中,你可以使用 em 和 % 单位。另外,在 jQuery 1.2 中,你可以通过在属性值前面指定 "<em>+=</em>" 或 "<em>-=</em>" 来让元素做相对运动。
jQuery 1.3中,如果duration设为0则直接完成动画。而在以前版本中则会执行默认动画。jQuery 1.8中,当你使用CSS属性在css()或animate()中,我们将根据浏览器自动加上前缀(在适当的时候),比如("user-select", "none"); 在Chrome/Safari浏览器中我们将设置为"-webkit-user-select", Firefox会使用"-moz-user-select", IE10将使用"-ms-user-select".
参数说明
params,[speed],[easing],[fn]Options,Number/String,String,FunctionV1.0
第一个参数: 接收一个对象, 可以在对象中修改属性
第二个参数: 指定动画时长
第三个参数: 指定动画节奏, 默认就是swing
第四个参数: 动画执行完毕之后的回调函数
demo实例
页面渲染
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title><style>*{margin: 0;padding: 0;}div{width: 100px;height: 100px;margin-top: 10px;background: red;}.two{background: blue;}</style><script src="js/jquery-1.12.4.js"></script></head><body><button>操作属性</button><button>累加属性</button><button>关键字</button><div class="one"></div><div class="two"></div></body></html>
demo1--操作属性
$("button").eq(0).click(function () {$(".one").animate({width: 500}, 1000, function () {alert("自定义动画执行完毕");});$(".two").animate({marginLeft: 500}, 5000, "linear", function () {// alert("自定义动画执行完毕");});});
当运行的时候,第一个div会宽度增加500px,第二个div会向左移动500px;
$(".one").animate({width: 500}, 1000, function () {alert("自定义动画执行完毕");});$(".one").animate({marginLeft: 500}, 5000, function () {// alert("自定义动画执行完毕");});
当一个div,有两个方法时,会根据顺序进行调用。
demo2--累加属性
$("button").eq(1).click(function () {$(".one").animate({width: "+=100"}, 1000, function () {alert("自定义动画执行完毕");});});
对第一个div实现宽度增加100px;
demo3--利用关键字修改属性
$("button").eq(2).click(function () {$(".one").animate({// width: "hide"width: "toggle"}, 1000, function () {alert("自定义动画执行完毕");});})
调用width: "toggle" 将第一个div进行隐藏。