简明现代魔法 -> JavaScript -> JavaScript简单的移动动画效果
JavaScript简单的移动动画效果
2011-06-24
一个JavaScript的笔试题,已知a、b,现在点鼠标a会向b游动,鼠标停,a会停下来,请实现"跑步算法"。其中用到的精髓是setInterval()方法,具体可以参照下面的代码。
效果演示
A
B
JavaScript Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>JavaScript</title>
<style>
.point1 { position:absolute; left:10px; top:40px; }
.point2 { position:absolute; left:100px; top:40px; }
.hr1 { position:absolute; top:60px; }
</style>
<script type="text/JavaScript">
document.onmousedown = mousedown;
document.onmouseup = mouseup;
var intervalProcess;
var direct = true;
function mousedown(){
intervalProcess = setInterval("MovePoint()", 1);
}
function mouseup(){
clearInterval(intervalProcess);
}
function MovePoint(){
with (document.getElementById("point1").style){
if (isNaN(parseInt(left)))
left = "10px";
else {
document.getElementById("point2").style.left = "200px";
if (parseInt(left) < 0)
direct = true;
if (parseInt(left) > parseInt(document.getElementById("point2").style.left))
direct = false;
if (direct)
left = parseInt(left) + 1 + "px";
else
left = parseInt(left) - 1 + "px";
}
}
}
</script>
<body>
<div class="point1" id="point1" style="width:25px; height:25px; background-color:blue;"></div>
<div class="point2" id="point2" style="width:25px; height:25px; background-color:green;"></div>
<hr class="hr1" />
</body>
自己建个HTML文件测试下更好。
