javascript寫加速勻速減速運動,瘋狂的自行車

一、HTML

<div id="road"></div>

<input type="button" value="請慢行" id="btn" />

<img src="zixingche2.gif" id="bicyle" />

<img src="80.png" id="maxSpeed" />

<img src="slow.jpg" id="slow" />

<img src="stop.jpg" id="stop" />

<textarea id="txt" cols="30" rows="10"></textarea>

二、CSS

*{

padding: 0px;

margin: 0px;

}

#road{

width: 100%;

height: 4px;

background: black;

margin-top: 300px;

}

#bicyle{

width: 100px;

height: 100px;

position: absolute;

top:200px;

left: 0px;

z-index: 2;

}

#maxSpeed{

width: 100px;

height: 100px;

position: absolute;

top: 200px;

left: 400px;

}

#slow{

width: 100px;

height: 100px;

position: absolute;

top:200px;

left: 800px;

}

#stop{

width: 100px;

height: 100px;

position: absolute;

top:200px;

left:1200px;

}

#btn{

position: absolute;

left: 0px;

top:304px;

}

#txt{

border:1px solid black;

position: absolute;

left: 50px;

top:304px;

overflow: auto;

}

三、script

javascript寫加速勻速減速運動,瘋狂的自行車

javascript寫加速勻速減速運動,瘋狂的自行車

window.onload=function(){

var oBtn=document.getElementById('btn');

oBtn.onclick=function(){

startMove();

}

}

function startMove(){

var oBicyle=document.getElementById('bicyle');

var oTxt=document.getElementById('txt');

var iSpeed=0;

timer=setInterval(function(){

if (oBicyle.offsetLeft<400) {

iSpeed+=8;

oBicyle.style.left=iSpeed+oBicyle.offsetLeft+'px';

}

else if (oBicyle.offsetLeft>=400 && oBicyle.offsetLeft<800) {

oBicyle.style.left=iSpeed+oBicyle.offsetLeft+'px';

}

else if (oBicyle.offsetLeft<1200 && oBicyle.offsetLeft>=800) {

iSpeed-=10;

if (iSpeed<=0) {

iSpeed=0;

clearInterval(timer);

}

oBicyle.style.left=iSpeed+oBicyle.offsetLeft+'px';

}

oTxt.innerHTML+=iSpeed+'-';

},30)

};

四、效果圖

javascript寫加速勻速減速運動,瘋狂的自行車

相關推薦

推薦中...