<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#div1{
background-color: yellow;
width: 100px;
height: 200px;
position: absolute;
left: 30px;
}
</style>
<script type="text/javascript">
window.onload = function () {
var oBtn1 = document.getElementById('btn1');
var oBtn2 = document.getElementById('btn2');
var oDiv = document.getElementById('div1');
var timer = null;
oBtn2.onclick = function(){
doMove(oDiv,800,12);
//*------在设置定时器的地方,先清除定时器,避免重复------*//
// clearInterval(timer);
// timer = setInterval(function(){
// var speed = parseInt(getStyle(oDiv,"left")) + 2;//19为步长
// if (speed > 800) {
// speed = 800
// }
// oDiv.style.left = speed + 'px';
// if (speed == 800) {
// clearInterval(timer);
// //alert(speed);
// }
// },200);
//*--------获取当前的样式的方法,并且存储起来--------*//
function getStyle(obj,attr){
return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr];
}
oBtn1.onclick = function(){
doMove(oDiv,10,-12);
}
// alert(parseInt(getStyle(oDiv,"left")));
function doMove(obj,target,dir){
clearInterval(timer);
timer = setInterval(function(){
var speed = parseInt(getStyle(oDiv,"left")) + dir;//19为步长
if (speed > target && dir>0 ||speed < target && dir<0) {
speed = target
}
//----------------整理代码-----------//
// if (speed < target && dir<0) {
// speed = target
// }
obj.style.left = speed + 'px';
if (speed == target) {
clearInterval(timer);
//alert(speed);
}
},200);
}
}
}
</script>
</head>
<body>
<input id="btn1" type="button" name="" value="往后">
<input id="btn2" type="button" name="" value="往前">
<div id="div1"></div>
</body>
</html>