Javascript simulates accelerated and decelerated motion code sharing

  • 2020-03-30 04:35:30
  • OfStack

Accelerated motion, that is, an object is moving faster and faster; Decelerate motion, that is, an object moves slower and slower. Now use Javascript to simulate both effects by using setInterval or setTimeout to dynamically change the distance between one element and another, such as xxx.style.left or xxx.style.marginleft, and then increase the speed each time you move.

Here are two examples:

Accelerated motion


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Accelerated motion </title>
<style type="text/css">
* {margin: 0; padding: 0;}
.div1 {width: 100px; height: 100px; background: #f60 url(qiuweiguan.gif) no-repeat center center;}
</style>
<script type="text/javascript">
var $$ = function (id) {
return document.getElementById(id);
}
window.onload = function () {
var oBtn = $$("btn1");
var oDiv = $$("div1");
var timer = null;
var speed = 0;
oBtn.onclick = function () {
clearInterval(timer);
timer = setInterval(function () {
speed ++;
oDiv.style.marginLeft = oDiv.offsetLeft + speed + "px";
}, 30);
}
}
</script>
</head>
<body id = "body">
<button id="btn1" class="btn1">GO</button>
<div id="div1" class="div1"></div>
</body>
</html>

Note: in this example, after clicking GO, the div block keeps accelerating to the right

Slow motion


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Slow motion </title>
<style type="text/css">
* {margin: 0; padding: 0;}
.div1 {width: 100px; height: 100px; background: #f60 url(qiuweiguan.gif) no-repeat center center;}
</style>
<script type="text/javascript">
var $$ = function (id) {
return document.getElementById(id);
} window.onload = function () {
var oBtn = $$("btn1");
var oDiv = $$("div1");
var timer = null;
var speed = 30;
oBtn.onclick = function () {
clearInterval(timer);
timer = setInterval(function () {
speed - ;
oDiv.style.marginLeft = oDiv.offsetLeft + speed + "px";
}, 30);
}
}
</script>
</head>
<body id = "body">
<button id="btn1" class="btn1">GO</button>
<div id="div1" class="div1"></div>
</body>
</html>


Related articles: