Sample index:
運動基礎
讓Div運動起來
速度- 物體運動的快慢
運動中的Bug
- 不會停止
- 速度取某些值會無法停止
- 到達位置後在點擊還會運動
- 重複點擊速度加快
右側懸浮框
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文件</title>
<style>
#div1
{
width:212px;
height:94px;
background:red;
position:absolute;
right:0;
bottom:0;
}
</style>
<script>
window.onscroll=function()
{
var oDiv=document.getElementById('div1');
var scrollTop= document.documentElement.scrollTop||document.body.scrollTop;
//oDiv.style.top = document.documentElement.clientHeight-oDiv.offsetHeight+scrollTop+'px';
startMove(parseInt((document.documentElement.clientHeight-oDiv.offsetHeight)/2+scrollTop));
}
var timer=null;
function startMove(iTarget)
{
var oDiv=document.getElementById('div1');
clearInterval(timer);
timer=setInterval(function()
{
var speed = (iTarget-oDiv.offsetTop)/10;
speed= speed>0?Math.ceil(speed):Math.floor(speed);
if (oDiv.offsetTop==iTarget)
{
clearInterval(timer);
}
else
{
oDiv.style.top = oDiv.offsetTop+speed+'px';
}
},30);
}
</script>
</head>
<body style="height:2000px;">
<div id="div1">
<img src="MCT_logo.png" />
</div>
</body>
</html>
勻速運動停止
- 速度不變
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文件</title>
<style>
#div1
{
width:100px;
height:100px;
background:red;
position:absolute;
left:0;
top:50px;
}
#div2{
width:1px;
height:300px;
position:absolute;
left:300px;
top:0;
background:#CCC;
}
#div3
{
width:1px;
height:300px;
position:absolute;
left:100px;
top:0;
background:#CCC;
}
</style>
<script>
//alert(Math.ceil(4.999)); //Output:5 (向上取整數)
//alert(Math.floor(4.999)); //Output:4 (向下取整數)
var timer= null;
function startMove(iTarget)
{
clearInterval(timer);
var oDiv=document.getElementById('div1');
timer=setInterval(function()
{
var speed =0 ;
if (oDiv.offsetLeft<iTarget)
{
speed = 7;
}
else
{
speed=-7;
}
if (Math.abs(iTarget-oDiv.offsetLeft)<=7)
{
clearInterval(timer);
oDiv.style.left=iTarget+'px';
}
else
{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
}
},30);
}
</script>
</head>
<body>
<input type="button" value="到100" onClick="startMove(100)" />
<input type="button" value="到300" onClick="startMove(300)" />
<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>
</body>
</html>