一架忌、運(yùn)動(dòng)框架
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>運(yùn)動(dòng)</title>
<style type="text/css">
#div1{width:100px;height:100px;position:absolute;background: red;left:0;top:50px;}
</style>
<script type="text/javascript">
var timer=null;
function startMove()
{
var oDiv=document.getElementById('div1');
clearInterval(timer);//防止點(diǎn)擊重復(fù)開定時(shí)器時(shí)物體運(yùn)動(dòng)加快
timer=setInterval(function(){
var iSpeed=7;
if(oDiv.offsetLeft>=300)//移動(dòng)300像素時(shí)停止(當(dāng)iSpeed=7 oDiv.offsetLeft==300 時(shí)不會(huì)停止移動(dòng)是由于300不能整除7)
{
clearInterval(timer);//到達(dá)300像素執(zhí)行
}
else
{
oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';//到達(dá)300像素之前執(zhí)行
}},30);
}
</script>
</head>
<body>
<input type="button" value="開始運(yùn)動(dòng)" onclick="startMove()"/>
<div id="div1"></div>
</body>
</html>
二、勻速運(yùn)動(dòng)
<meta charset="utf-8">
<title>運(yùn)動(dòng)</title>
<style type="text/css">
#div1{width:100px;height:100px;position:absolute;background: red;left:500px;top:50px;}
</style>
<script type="text/javascript">
var timer=null;
function startMove(iTarget)
{
var oDiv=document.getElementById('div1');
clearInterval(timer);
timer=setInterval(function(){
var iSpeed=0;
if(oDiv.offsetLeft<iTarget)
{
iSpeed=7;
}
else
{
iSpeed=-7;
}
if(Math.abs(oDiv.offsetLeft-iTarget)<7)//兩個(gè)之間的距離已經(jīng)足夠近丁恭,連一次運(yùn)動(dòng)都完不成了
{
clearInterval(timer);//達(dá)到終點(diǎn)
oDiv.style.left=iTarget+'px';
}
else
{
oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';//到達(dá)終點(diǎn)之前執(zhí)行
}},30);
}
</script>
</head>
<body>
<input type="button" value="開始運(yùn)動(dòng)" onclick="startMove(300)"/>
<div id="div1"></div>
<span style="width: 1px;height:300px;background: black;position: absolute;left: 300px;top:0;"></span>
</body>
</html>
三曹动、緩沖運(yùn)動(dòng)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>運(yùn)動(dòng)</title>
<style type="text/css">
#div1{width:100px;height:100px;position:absolute;background: red;left:0;top:50px;}
</style>
<script type="text/javascript">
var timer=null;
function startMove(iTarget)
{
var oDiv=document.getElementById('div1');
clearInterval(timer);
timer=setInterval(function(){
var iSpeed=(iTarget-oDiv.offsetLeft)/8;
if(oDiv.offsetLeft>=iTarget)
{
clearInterval(timer);
}
else
{
oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';
// txt1.value+=iSpeed+'\n';
}},30);
}
</script>
</head>
<body>
<input type="button" value="開始運(yùn)動(dòng)" onclick="startMove(300)"/>
<div id="div1"></div>
<!--
<textarea id="txt1" rows="10" cols="40"> </textarea>
-->
</body>
</html>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者