SoFunction
Updated on 2025-03-09

JS constant speed motion demonstration sample code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/">
<html xmlns="http:///1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Constant Speed ​​Movement Demonstration</title>
<style type="text/css">
<!--

#div1 {width:1px;height:200px;background-color: black;position:absolute;left:100px;top:70px;float:left}
#div1 span {position:absolute;top:-15px}
#div2 {width:1px;height:200px;background-color:midnightblue;position:absolute;left:800px;top:70px;float: left}
#div2 span {position:absolute;top:-15px}
#div3 {width:1px;height:200px;background-color:fuchsia;position:absolute;left:300px;top:70px;float: left}
#div3 span {position:absolute;top:-15px}
#div4 {width:1px;height:200px;background-color:darkmagenta;position:absolute;left:500px;top:70px;float: left}
#div4 span {position:absolute;top:-15px}
#grap {width:200px;height:200px;background:red;position:absolute;left:300px;top:74px;float: left;}
input {width:100px;margin-left: 90px;}
-->
</style>
<script type="text/javascript">
var timeId
function startMove(target){
var oDiv=('grap')
clearInterval(timeId); //This place is to prevent multiple clicks from accelerating. It is very important
speed=<target?8:-9;
timeId=setInterval(function(){
if((-target)<=6){
=target+'px'; //As long as the rectangle moves to the target point, it will move directly to the target point, and the naked eye cannot detect the change in speed
clearInterval(timeId); ="target"+;
}
else{
=+speed+'px';
}
},30);
}
</script>
</head>
<body>
<div ><span>100px</span></div>
<div ><span>800px</span></div>
<div ><span>300px</span></div>
<div ><span>500px</span></div>
<input type="button" value="Move to 100px" onclick="startMove(100)"/>
<input type="button" value="Move to 300px" onclick="startMove(300)"/>
<input type="button" value="Move to 500px" onclick="startMove(500)"/>
<input type="button" value="Move to 800px" onclick="startMove(800)"/>
<div ></div>

</body>
</html>