封装缓动动画回掉函数:
<!DOCTYPE html>
<html>
<head>
<title>封装运动函数回掉函数</title>
<style type="text/css">
div {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 50px;
border-radius: 50%;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="box"></div>
</body>
</html>
<script type="text/javascript">
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
var box = document.getElementById("box");
btn200.onclick = function() {
animate(box,{width: 200, top: 800,left: 200},function(){alert("我好了,你呢")});
}
btn400.onclick = function() {
animate(box,{top:500});
}
function animate(obj, json, fn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var flag = true; // 用来判断是否停止定时器
for(var attr in json){
var current = parseInt(getStyle(obj, attr));
var step = (json[attr] - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
obj.style[attr] = current + step + "px";
if (current != json[attr]) {
flag = false
}
}
if (flag) {
clearInterval(obj.timer);
fn();
}
}, 30);
}
//获取样式属性值
function getStyle(obj, attr){
if (obj.currentStyle) {
// IE浏览器识别
return obj.currentStyle[attr];
} else {
return window.getComputedStyle(obj, null)[attr];
}
}
</script>