HTML部分:
<button id="btn">移动</button>
<button id="btn1">往左</button>
<div id="box" class="box"></div>
CSS部分:
*{
margin: 0;
padding: 0;
border:none;
}
div{
width: 100px;
height: 100px;
border:1px solid #ccc;
background: red;
position: absolute;
}
JS部分:
window.onload = function(){
1.获取标签
var btn = document.getElementById('btn');
var btn1 = document.getElementById('btn1');
var box = document.getElementById('box');
2.点击按钮实现动画
btn.onclick = function(){
constant(box,800,4);
};
btn1.onclick = function(){
constant(box,0,4);
}
0.封装函数用来表示匀速动画
(obj:表示进行动画的标签)
(target:表示目标值)
(speed:表示速度)
function constant(obj,target,speed){
清空定时器
clearInterval(obj.timer);
obj.timer = setInterval(function(){
根据方向来确定速度正负值
var mySpeed = target > obj.offsetLeft?speed:-speed;
obj.style.left = obj.offsetLeft + mySpeed +'px';
if(Math.abs(target - obj.offsetLeft) < Math.abs( mySpeed))
{
clearInterval(obj.timer);
obj.style.left = target +'px';
}
},20)
}
}