视频链接:
视频链接
定时器03.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box1{
width: 100px;
height: 100px;
background-color: #6495ED;
position: absolute;
left:0;
}
#box2{
width: 100px;
height: 100px;
background-color: #FFFF00;
position: absolute;
left:0;
top:200px;
}
#line{
width: 0;
height: 1000px;
border-left:1px black solid;
position: absolute;
left:800px;
top: 0;
}
</style>
<script src="./js/tools.js" type="text/javascript"></script>
<script type="text/javascript" >
/**
* 所有正在执行的定时器都在这个变量中保存
*/
//var timer;
window.onload=function(){
var box1=document.getElementById("box1");
var box2=document.getElementById("box2");
var btn01=document.getElementById("btn01"); //点击按钮以后box1向右移动
var btn02=document.getElementById("btn02");//点击按钮以后box1向左移动
var btn03=document.getElementById("btn03");//box1你停下来
var btn04=document.getElementById("btn04");//点击按钮以后box2向右移动
var btn05=document.getElementById("btn05");//测试按钮
var btn06=document.getElementById("btn06");//box2你停下来
btn01.onclick=function(){//点击按钮以后box1向右移动
move(box1,"left",800,10);
}
btn02.onclick=function(){//点击按钮以后box1向左移动
move(box1,"left",0,10);
}
btn04.onclick=function(){//点击按钮以后box2向右移动
move(box2,"left",800,10);
}
btn05.onclick=function(){//测试按钮
// move(box2,"width",800,10);
// move(box2,"top",800,10);
// move(box2,"height",800,10);
move(box2,"height",800,10,function(){
move(box2,"width",800,10,function(){
//这里我就不套娃了
});
});
}
//box1你停下来
btn03.onclick=function(){
stop(box1);
}
//box2你停下来
btn06.onclick=function(){
stop(box2);
}
}
</script>
</head>
<body>
<button id="btn01">点击按钮以后box1向右移动</button>
<button id="btn02">点击按钮以后box1向左移动</button>
<button id="btn04">点击按钮以后box2向右移动</button>
<button id="btn05">测试按钮</button>
<br /> <br />
<button id="btn03">box1你停下来</button>
<button id="btn06">box2你停下来</button>
<br /> <br />
<div id="box1"></div>
<div id="box2"></div>
<div id="line" ></div>
</body>
</html>
js:tools.js
/**
* 创建一个可以执行简单动画的函数
* obj:执行对象
* attr:要执行动画的样式
* speed:移动速度(有正负)正数向右 负数向左
* target:执行动画的目标位置
* callback:回调函数 在动画执行完毕之后执行
*/
function move(obj,attr,target,speed,callback){
//开启一个定时器 执行动画效果
clearInterval(obj.timer);
//判断速度的正负 如果从0到800 移动 speed大于0 反之小于0
var current=parseInt(getStyle(obj,attr));//元素目前的位置
if(current>target) {
speed=-speed;
}
obj.timer=setInterval(function(){
// box1.style.left=box1.offsetLeft-10+"px";
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 stop(obj){
clearInterval(obj.timer);
}
/**
* 定义一个函数用来获取指定元素当前的样式
*/
function getStyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];// //正常浏览器的方式 // return getComputedStyle(obj,null)[name];
}else{
return obj.currentStyle[name]; // //IE8的方式 // return obj.currentStyle[name];
}
}