<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
#box1{
width:100px;
height:100px;
background-color:red;
position:absolute;
left:0px;
}
#box2{
width:100px;
height:100px;
background-color:yellow;
position:absolute;
left:0px;
top:200px;
}
</style>
<script type="text/javascript" src="js/tools.js"></script>
<script type="text/javascript">
window.onload=function(){
var box1=document.getElementById("box1");
var btn01=document.getElementById("btn01");
var btn02=document.getElementById("btn02");
var box2=document.getElementById("box2");
//点击按钮以后,使Box1 向右移动
btn01.onclick=function(){
move(box1,"left",800,20);
};
// 点击按钮以后,使box1 向左进行移动
btn02.onclick=function(){
move(box1,"left",0,10);
};
// 获取btn03
var btn03=document.getElementById("btn03");
btn03.onclick=function(){
move(box2,"left",800,10);
};
var btn04=document.getElementById("btn04");
btn04.onclick=function(){
move(box2,"width",800,10,function(){
move(box2,"height",400,10,function(){
move(box2,"top",0,10,function(){
move(box2,"width",100,10,function(){});
});
});
});
};
};
</script>
</head>
<body>
<button id="btn01">点击按钮以后box1向右移动</button>
<button id="btn02"> 点击按钮以后 box1 向左移动</button>
<button id="btn03">点击按钮以后 box 2 向右移动</button>
<button id="btn04">测试按钮</button>
<br/>
<br/>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
js/tools.js:
// 尝试创建一个可以执行简单动画的函数
// 参数:obj 表示要执行动画的对象,
// attr: 表示的使要执行动画的样式,比如 left,top,width innerHeight,
// target: 表示的使要执行动画的目标位置,
// speed: 表示的是要执行的速度,
// callback:表示的是回调函数,这个函数表示的将会在动画执行完毕以后执行,
function move(obj,attr,target,speed,callback){
//关闭上一个定时器
clearInterval(obj.timer);
//获取元素目前的位置
var current=parseInt(getStyle(obj,attr));
//判断速度的正负值
//也就是如果从0 向800移动的话,则speed 的值为正
//否则的话如果从800向0移动的话,则speed 为负值
if(current>target){
//此时速度为负值
speed=-speed;
}
//开启一个定时器,用来执行动画效果
// 向执行动画的对象中添加一个timer属性,用来保存他自己的定时器的标识
obj.timer=setInterval(function(){
//获取元素原来的 left 值
var oldValue=parseInt(getStyle(obj,attr));
//在旧值的基础上增加
var newValue=oldValue+speed;
//判断newValue 的值是否大于800
//向左移动的时候,需要判断newValue 的值是否小于target
// 向右移动的时候,需要判断newValue 的值是否大于target
if((speed>0&&newValue>target)||(speed<0&&newValue<target)){
newValue=target;}
//将新值赋值给box1
obj.style[attr]=newValue+"px";
//当元素移动到0px 的时候, 使其停止执行动画
if(newValue==target){
//达到目标,关闭定时器
clearInterval(obj.timer);
// 动画执行完毕,此时调回回调函数
callback&&callback();
}
},30);}
//这是用来定义一个函数,用来治党获取元素当前的样式
// 参数是:
//obj 表示的是要获取样式的元素
//name 表示的示要获取的样式名
// 注意这边getComputedStyle 的方法第一个参数填的是参数,第二个参数填的是 是否有伪元素
//如果没有的话 就填null
// 一般情况下是这样调的:
//window.getComputedStyle(obj,null).name; 但是 js 中可以用中括号去代替点
function getStyle(obj,name){
if(window.getComputedStyle){
//正常浏览器的方式,具有getComputedStyle 的 方法
return getComputedStyle(obj,null)[name];
}else{
//IE8 的方式,没有 getComputedStyle () 的方法
return obj.currentStyle[name];
}
}
运行结果图: