animate原生

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
/*因为要运动, 所以要定位*/
position: absolute;
background-color: red;
top: 100;
left: 100;
}

</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
// 我们要让box以动画方式 运动到1000的位置
// 获取元素
var box = document.getElementById("box");


// $("xx").animate({}, 1000, function() {})


/*
* animate 实现动画函数
* @dom 要运动的元素
* @json css样式对象
* @callback 回到函数
*/




function animate(dom, json, time, callback) {
// 计数器
var count = 0;
// 总次数 = 总距离 / 步长
// 总次数 = 总时间 / 间隔时间
// 定义一个间隔时间
var interval = 20;
// 定义总次数
var allCount = time / interval;
// json里面的每一个属性都是一个目标值
// 我们要知道初始值,就可以计算出总距离
// json里面有多少目标值 , 我们就应该多少初始值
var nowJson = {


};
// 该对象用来 存储初始状态, 要根据json里面的内容决定
for (var i in json) {
// console.log(i);
nowJson[i] = parseInt(getComputedStyle(dom)[i]);


}
// console.log(nowJson)
// 循环完毕之后 初始值也就有了
// 在计算总距离和步长值


// 定义用于存储步长值的对象
var stepJson = {


};
for (var i in json) {
stepJson[i] = (json[i] - nowJson[i]) / allCount;
}
console.log(stepJson);
// 循环完毕后, 步长值就有了
// 定时器
var timer = setInterval(function() {
// 计算器
count++;
// 改变dom css值
for (var i in json) {
// 当前值 = 初始值 + 步长值 * 次数
dom.style[i] = nowJson[i] + stepJson[i] * count + "px"
console.log(stepJson[i]);
}


// 判断是否到达目标位置
if (count >= allCount) {
// 停表
clearInterval(timer)
// 执行回调函数
callback && callback()
}
}, interval)
}
// 执行
animate(box, {left: 999, top: 444.3}, 999, function() {
console.log("动画完成了")
})






</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/liux6687/article/details/80443832
今日推荐