<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#box{
position: relative;
top: 100px;
left: 100px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="box"></div>
<button>向左</button> <button>向右</button> <button>向上</button> <button>向下</button> <button>变宽</button>
<script src="./tools.js"></script>
<script>
var oBox = document.getElementById('box');
var oLeft = document.getElementsByTagName('button')[0];
var oRight = document.getElementsByTagName('button')[1];
var oTop = document.getElementsByTagName('button')[2];
var oBottom = document.getElementsByTagName('button')[3];
var oWidth = document.getElementsByTagName('button')[4];
var timer = null;
oRight.onclick = function(){
move(10,500,'left');
}
oLeft.onclick = function(){
move(10,0,'left');
}
oTop.onclick = function(){
move(10,0,'top');
}
oBottom.onclick = function(){
move(10,400,'top');
}
oWidth.onclick = function(){
move(5,400,'width');
}
function move(step,target,attr){ // step: 步长 target:目标值 attr:要运动的样式属性
clearInterval(timer);
var current = parseInt(getCss(oBox,attr));//获取当前值
step = target >= current ? step : -step; //根据目标值判断方向
timer = setInterval(function(){
current+=step;
if(step>0&¤t>=target || step<0&¤t<=target){
clearInterval(timer);
current = target;
}
oBox.style[attr] = current + 'px';
},20);
}
</script>
</body>
</html>
实现效果如下