通过按钮控制box位置移动和大小变换。
定时器和自定义函数的应用。
回调函数可以有很神奇的效果。
HTML文件:
<!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: yellowgreen;
position: absolute;
left: 0;
top: 200px;
}
</style>
</head>
<body>
<button id="btn01">点击按钮box1向右移动</button>
<button id="btn02">点击按钮box1向左移动</button>
<button id="btn03">点击按钮box2向右移动</button>
<button id="btn04">点击按钮box2多种运动</button>
<br /><br />
<div id="box1"></div>
<div id="box2"></div>
<div style="width: 0px; height: 1000px; border-left: 1px black solid; position: absolute; left: 800px; top: 0;"></div>
</body>
<script type="text/javascript" src="js/move.js" ></script>
<script>
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
//点击按钮以后,box1向右移动(left增大)
btn01.onclick = function() {
move(box1, "left", 800, 10);
};
//点击按钮以后,box1向左移动(left减小)
btn02.onclick = function() {
move(box1, "left", 0, 10);
};
var btn03 = document.getElementById("btn03");
btn03.onclick = function() {
move(box2, "left", 800, 20);
};
var btn04 = document.getElementById("btn04");
btn04.onclick = function() {
move(box2, "width", 800, 10, function() {
move(box2, "height", 400, 10, function() {
move(box2, "height", 100, 10, function() {
move(box2, "width", 100, 10);
});
});
});
};
</script>
</html>
把js代码提取出来,js文件:
//定义一个函数,获取当前样式
function getStyle(obj, name) {
if(window.getComputedStyle) {
//正常浏览器
return getComputedStyle(obj, null)[name];
} else {
//IE8
return obj.currentStyle[name];
}
};
//定义一个变量,用来标识定时器
//var timer;
//创建一个可以执行简单动画的函数
/*
* 参数:
* obj:要执行动画的对象
* attr:要执行动画的样式 比如:left top height width
* target:执行动画的目标位置
* speed:移动的速度(正数向右移动,负数向左移动)
* callback:回调函数,将会在动画执行完毕后执行
*/
function move(obj, attr, target, speed, callback) {
//关闭上一个定时器
clearInterval(obj.timer);
//获取元素目前的位置
var current = parseInt(getStyle(obj, attr));
//判断速度的正负值
if(current > target) {
//此时速度为负值
speed = -speed;
}
//开启一个定时器,执行动画效果
//想执行动画的对象中添加一个timer属性,保存它自己的定时器标识
obj.timer = setInterval(function() {
//获取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;
}
//将新值设置给obj
obj.style[attr] = newValue + "px";
//当obj移动到target时,停止移动
if(newValue == target) {
//达到目标,关闭定时器
clearInterval(obj.timer);
//动画执行完毕,调用回调函数
callback && callback();
}
}, 30);
};