jQuery animate() 方法允许您创建自定义的动画。
语法:
$(selector).animate({params},speed,callback);
注意:
必需的 params 参数定义形成动画的 CSS 属性。
可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
可选的 callback 参数是动画完成后所执行的函数名称。
提示:
默认地,所有 HTML 元素都有一个静态位置,且无法移动。
如需对位置进行操作,要记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute!
实例1:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left:'250px'});
});
});
</script>
</head>
<body>
<button>开始动画</button>
<div style="background:gold;height:100px;width:100px;position:absolute;">
</div>
</body>
</html>
实例2:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left:'250px',
opacity:'0.5',
height:'150px',
width:'150px'
});
});
});
</script>
</head>
<body>
<button>开始动画</button>
<div style="background:gold;height:100px;width:100px;position:absolute;">
</div>
</body>
</html>
实例3:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div=$("div");
div.animate({left:'100px'},"slow");
div.animate({fontSize:'3em'},"slow");
});
});
</script>
</head>
<body>
<button>开始动画</button>
<div style="background:gold;height:100px;width:200px;position:absolute;">HELLO</div>
</body>
</html>
当然你也可以使用callback函数,
Callback 函数在当前动画 100% 完成之后执行,比如说动画结束后弹出一个警告框:
<html>
<head>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left:'0px',
opacity:'0.5',
height:'700px',
width:'1336px',
fontSize:'36em'
},1000,function(){
alert("animation end");
var div=$("div");
div.animate({left:'10px',height:'100px',width:'100px'},"slow");
div.animate({fontSize:'3em'},"slow");
});
});
});
</script>
</head>
<body>
<button type="button">click me</button>
<div style="color:red;background:gold;height:100px;width:100px;position:absolute;">shit</div>
</body>
</html>