<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="../js/tools.js"></script>
<title>Document</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: yellow;
position: absolute;
left: 0;
top: 200px;
}
</style>
<script>
window.onload = function(){
// btn01
var btn01 = document.getElementById("btn01");
var box1 = document.getElementById("box1");
var btn02 = document.getElementById("btn02");
var btn03 = document.getElementById("btn03");
var btn04 = document.getElementById("btn04");
btn01.onclick = function(){
move(box1,"left",800,20);
}
btn02.onclick = function(){
move(box1,"left",0, 10);
}
btn03.onclick = function(){
move(box2,"left",800, 10);
}
btn04.onclick = function(){
// move(box2,"width",800, 10);
move(box2,"width",800, 10,function(){
move(box2,"height",400, 10,function(){
move(box2,"top",0, 10,function(){
move(box2,"width",100, 10,function(){
move(box2,"height",100, 10,function(){
move(box2,"top",200, 10);
});
});
});
});
});
}
// 定义一个变量 用来保存定时器的标识
/**
* 参数
* obj 要执行动画的对象
* attr 要执行动画的样式 例如: left top width height
* target 执行动画的目标
* speed 移动的速度 (正数向右移动 负数向左移动)
* callback: 回调函数 这个函数将会在动画执行完成以后执行
*/
// var timer;
// 封装动画函数
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(() => {
// 获取 box1 原来的left 值
var oldValue = parseInt(getStyle(obj,attr));
// 在 旧值的基础上增加
var newValue = oldValue + speed;
// 向左移动时 需要判断 newValue 是否小于 target
// 向右移动时 需要判断 newValue 是否大于 target
if(speed < 0 && newValue < target || (speed > 0 && newValue > target)){
newValue = target;
}
// 将新值 设置给box1
obj.style[attr] = newValue + ‘px‘;
// 当元素移动到 800px时, 使其停止执行动画
if(newValue == target){
clearInterval(obj.timer);
// 动画执行完毕 调用回调函数
callback && callback();
}
}, 30);
}
/**
* 定义一个函数 用来获取指定元素的当前的样式
* 参数
* obj 要获取样式的元素
* name 要获取的样式名
*/
function getStyle(obj,name){
if(window.getComputedStyle){
// 正常浏览器的方式
return getComputedStyle(obj,null)[name];
}else{
// ie8 的方式
return obj.currentStyle[name];
}
}
}
</script>
</head>
<body>
<button id="btn01">点击以后box1向右移动</button>
<button id="btn02">点击以后box2向左移动</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 solid black;position: absolute;left: 800px;top:0;"></div>
</body>
</html>