复制代码
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// 参数: // obj:要执行动画的对象; // attr:要执行动画的样式,如"left" "top" "height" "width" //target: 执行动画的目标位置 //speed:移动的速度 //callback:回调函数,将在动画执行完毕后执行 // var timer; function move(obj,attr,target,speed,callback){ clearInterval(obj.timer);//关闭上一个定时器 var current = parseInt(getStyle(obj,attr));//获取obj当前位置 if(current > target){ speed = - speed;//如果当前位置大于目标位置,应该向左移动,速度为负值 } obj.timer = setInterval(function(){ var oldValue = parseInt(getStyle(obj,attr));//获取obj原来的位置 var newValue = oldValue + speed;//设置obj移动 if((speed < 0 && newValue < target) || (speed > 0 && newValue > target)){ newValue = target;//不能让移动超过边界 } obj.style[attr] = newValue + "px";//设置obj现在的位置 if(newValue == target){//如果obj到达目标位置,则停止移动,清除定时器 clearInterval(obj.timer); callback && callback(); } },30); }; function getStyle(obj,name){ if(window.getComputedStyle){ return getComputedStyle(obj,null)[name]; }else{ return obj.currentStyle[name]; }; }
最后
以上就是冷酷御姐最近收集整理的关于封装move函数—基于原生JS的全部内容,更多相关封装move函数—基于原生JS内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复