视频地址:https://b23.tv/BV1YW411T7GX/p133
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
}
</style>
<script type="text/javascript">
window.onload=function(){
//获取box1
var box1 =document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick = function(){
move(box1,'width',800,10,function(){
move(box1,'height',400,10,function(){
move(box1,'top',100,10,function(){
move(box1,'width',100,10,function(){
move(box1,'height',100,10,function(){
move(box1,'top',45,10)
})
})
})
})
})
}
//尝试创建一个可以执行简单动画的函数;
/*
*参数
* obj:要执行动画的对象
* attr:要执行动画的样式,比如left,top,width,height
* target:要执行动画的位置
* speed:移动的速度(正数向右移动,负数向左移动)
* callback:回调函数,这个函数会在动画执行完毕后执行
*/
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;
//判断速度的正负值
//如果从0向800移动,则speed为正
//向左移动时,需要判断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要获取的样式名
function getStyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
return obj.currentStyle[name];
}
}
}
</script>
<body>
<button id="btn01">box1向右移动</button>
<br><br>
<div id="box1"></div>
<div style="width: 0;height: 1000px;border-left: 1px solid black;position: absolute;left: 800px ;top: 0;"></div>
</body>
</html>