HTML部分:
<button id="btn">移動(dòng)</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.獲取標(biāo)簽
var btn = document.getElementById('btn');
var btn1 = document.getElementById('btn1');
var box = document.getElementById('box');
2.點(diǎn)擊按鈕實(shí)現(xiàn)動(dòng)畫(huà)
btn.onclick = function(){
constant(box,800,4);
};
btn1.onclick = function(){
constant(box,0,4);
}
0.封裝函數(shù)用來(lái)表示勻速動(dòng)畫(huà)
(obj:表示進(jìn)行動(dòng)畫(huà)的標(biāo)簽)
(target:表示目標(biāo)值)
(speed:表示速度)
function constant(obj,target,speed){
清空定時(shí)器
clearInterval(obj.timer);
obj.timer = setInterval(function(){
根據(jù)方向來(lái)確定速度正負(fù)值
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)
}
}