<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0%;
padding: 0%;
}
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0px;
}
#box2 {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
left: 0px;
top: 400px;
}
</style>
<script>
window.onload = function () {
//获取按钮btn01、btn02和盒子box1
var btn01 = document.getElementById("btn01");
var btn02 = document.getElementById("btn02");
var box1 = document.getElementById("box1");
//点击按钮后使box1移动
//为btn01绑定单击事件
btn01.onclick = function () {
move(box1, 800, 10);
};
//为btn02绑定单击事件
btn02.onclick = function () {
move(box1, 0, 10);
};
//获取按钮btn03、btn04和盒子box2
var btn03 = document.getElementById("btn03");
var btn04 = document.getElementById("btn04");
var box2 = document.getElementById("box2");
//点击按钮后使box2移动
//为btn03绑定单击事件
btn03.onclick = function () {
move(box2, 800, 10);
};
//为btn04绑定单击事件
btn04.onclick = function () {
move(box2, 0, 10);
};
//尝试创建一个可以执行简单动画的函数
/**
* 参数:
* onj:移动的对象
* target:执行动画的目标位置
* spead:移动的速度
*/
function move(obj, target, spead) {
//关闭上一个开启的定时器
clearInterval(obj.timeID);
//获取box1最初的位置
var current = obj.offsetLeft;
//判断速度的方向,如果开始位置大于目标位置,则为负方向
if(current>target){
spead = -spead;
}
//向执行的动画的对象添加一个timeID属性,用来自己的保存定时器标识
//开启定时器,来执行动画效果
obj.timeID = setInterval(function () {
//获取box1最初的left
var oldValue = obj.offsetLeft;
//在旧值上增加
var newValue = oldValue + spead;
//将新值赋给obj
obj.style.left = newValue + "px";
//当newVaule达到目标位置时,停止
if (spead > 0 && newValue >= target || spead < 0 && newValue <= target) {
newValue = target;
clearInterval(obj.timeID);
}
}, 30);
}
};
</script>
</head>
<body>
<button id="btn01">点我box1向右移动</button>
<button id="btn02">点我box1向左移动</button>
<button id="btn03">点我box2向右移动</button>
<button id="btn04">点我box2向左移动</button>
<div style="width: 0px; height: 1000px; border-left: 1px solid black; position: absolute; left: 800px; top: 0px;">
</div>
<br><br><br>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
12-05
11-12
402