定时器练习
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>定时器的应用</title>
<style>
*{
margin:0;
padding: 0;
}
#box1{
width:100px;
height: 100px;
background-color: red;
position: absolute;
left:0;
}
#box2{
width:100px;
height: 100px;
background-color: greenyellow;
position: absolute;
left:0;
top :200px;
}
</style>
<script>
window.onload=function(){
var box1=document.getElementById("box1");
var box2=document.getElementById("box2");
var btn01=document.getElementById("btn01");
var btn02=document.getElementById("btn02");
btn01.onclick=function(){
move(box1,"left",800,10);
}
btn02.onclick=function(){
move(box1,"left",0,10);
}
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(){
});
});
});
}
function move(obj,attr,target,speed,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();
}
},30)
}
function getStyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
return obj.currentstyle[name];
}
}
}
</script>
</head>
<body>
<button id="btn01">点击按钮以后box1向右移动</button>
<button id="btn02">点击按钮以后box1向左移动</button>
<button id="btn03">点击按钮以后box2向右移动</button>
<button id="btn04">测试按钮</button>
<br>
<br>
<div id="box1"></div>
<div id="box2"></div>
<div style="width:0; height: 1000px; border-left:1px black solid; position:absolute; left: 800px;top:0;"></div>
</body>
</html>