JS函数move(obj,attr,target,speed,interval,callback)
//功能:以定时器方式设置元素长宽伸缩或水平/垂直移动的动画
//要求:元素样式必须设置绝对定位,并且有left和top属性
//obj:要执行动画的对象
//attr:要改变的属性,比如:left top width height
//target:执行动画的目标位置
//speed:移动的速度
//callback:在动画执行完毕之后执行
function move(obj,attr="left",target=800,speed=1,interval=5,callback){
clearInterval(obj.timer)//清除定时器
var current=parseInt(getStyle(obj,attr));//获取当前元素位置
if(current>target){//判断方向
speed=-speed
}
obj.timer=setInterval(function(){
//获取上一次移动时的值
var oldValue=parseInt(getStyle(obj,attr));
//获取新值
var newValue=oldValue+speed;
//判断是否超过目标值,若超过则设置新值等于目标值
if((speed<0&&newValue<target)||(speed>0&&newValue>target)){
newValue=target
}
obj.style[attr]=newValue+"px" //设置样式
//若新值等于目标值则清除定时器
if(newValue==target){
clearInterval(obj.timer);
callback&&callback();
}
},interval)
}
//获取元素当前属性
function getStyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
return obj.currentStyle[name]
}
}
html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box1{
width: 40px;
height: 40px;
background-color: red;
position: absolute;
top: 50px;
left: 0px;
}
#box2{
width: 40px;
height: 40px;
background-color: yellow;
position: absolute;
top: 100px;
left: 0px;
}
</style>
</head>
<body>
<div id="box1">这是DIV1</div>
<div id="box2">这是DIV2</div>
<button type="button" id="btn">按钮1</button>
<button type="button" id="btn2">按钮2</button>
<div style="width: 1px;height: 800px;background-color: black;position: absolute;left: 800px;"></div>
</body>
<script src="move.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var box1=document.getElementById("box1");
var box2=document.getElementById("box2");
var btn1=document.getElementById("btn");
var btn2=document.getElementById("btn2");
var timer;//定时器变量
btn1.onclick=function(){
move(box1)
}
btn2.onclick=function(){
move(box2,"width",800,1,function(){console.log("动画执行完成")})
}
</script>
</html>