<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#box {
width: 100px;
height: 100px;
background-color: greenyellow;
position: absolute;
}
</style>
</head>
<body>
<input type="button" value="按钮" id="btn"/>
<div id="box"></div>
<script>
var btn = document.getElementById("btn");
btn.onclick = function () {
animate(box, {"height": 400, "width": 400, "borderRadius": 150, "left": 100, "top": 100}, function () {
animate(box, {"height": 200, "width": 100, "borderRadius": 20, "left": 200, "top": 50}, function () {
animate(box, {"height": 100, "width": 200, "borderRadius": 100, "left": 400, "top": 400})
})
})
}
function animate(obj, json, fn) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var isTrue = true;
for (var k in json) {//{k:json[k]}
var leader = parseInt(getAttr(obj, k)) || 0;//如果是nan的话,给一个默认值
var step = (json[k] - leader) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);//做一个判断,当step>0的时候,向上取整,保证至少为一;<0的时候,向下取整,保证至少为-1
leader = leader + step;
obj.style[k] = leader + "px";
console.log("代码还在执行");
if (leader != json[k]) {
isTrue = false;
}
}
if (isTrue) {
clearInterval(obj.timer);
if (fn) {
fn();
}
}
}, 15);
}
function getAttr(demo, attr) {
if (window.getComputedStyle) {
return window.getComputedStyle(demo, null)[attr];
} else {
return demo.currentStyle[attr];
}
}
</script>
</body>
</html>
使用原生的javascript封装动画函数(有callback功能)
原文:https://www.cnblogs.com/7qin/p/9602209.html