四、animate函数

四、animate函数

1
2
3
4
5
6
7
8
#box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50px;
left: 50px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 获取box
var box = document.getElementById("box");
// 改变box位置
animate(box, {"left": 1000, "top": 300}, 1000, function(){
alert("动画完成了");
});

// $(xx).animate({}, time, callBack);

// 封装函数,实现animate方法
// @dom 表示要运动的元素
// @json css样式
// @time 要完成动画的时间 单位ms
// @callBack 回调函数
function animate(dom,json,time,callBack){
/*
逻辑分析:
定义间隔定时器,循环动画到目标值
既然是循环动画,那么每一次动画都是一个步长
步长值 = 总距离 / 总次数
总距离 = 目标值 - 初始值
总次数 = 总时间 / 定时器间隔时间
*/

// 计数器
var count = 0;
// 定义间隔时间
var interval = 20;
// 总次数 = 总时间 / 间隔时间
var allCount = time / interval;

// 获取元素的总距离,就是用目标值 - 初始值
// json里面传递的都是目标值
// 定义一个nowJson 用于保存元素的初始值
var nowJson = {};
for (var i in json){
// console.log(i); // left top
// nowJson[i] = getComputedStyle(dom)[i]; // {left: "50px", top: "50px"} 字符串类型
// 转为number类型
nowJson[i] = parseInt(getComputedStyle(dom)[i]); // {left: 50, top: 50}
}
// console.log(nowJson);
// 循环完毕之后初始值也就有了

// 计算总距离,再得到步长值
var stepJson = {};
for (var i in json){
// 步长值 = (目标值 - 初始值)/ 总次数
stepJson[i] = (json[i] - nowJson[i]) / allCount
}
// console.log(stepJson); // {left: 19, top: 9}

// 定义定时器
var timer = setInterval(function(){
// 计数器++
count ++;
// 改变dom的定位值
for (var i in json){
// 当前值 = 初始值 + 步长值 * 次数
dom.style[i] = nowJson[i] + stepJson[i] * count + "px";
}
// 判断是否到达边界
if (count >= allCount){
// 停止定时器
clearInterval(timer);
// 执行回调函数 短路语法 存在callBack 执行后面的,不存在就执行前面的
callBack && callBack();
}
}, interval);
}

UMAUxK.png

点击查看

本文标题:四、animate函数

文章作者:Mango

发布时间:2020年07月13日 - 22:16:56

最后更新:2020年07月15日 - 13:28:19

原始链接:https://mango185.github.io/post/bbd4025.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------