Accelerated movement means that an object is moving faster and faster; decelerated movement means that an object is moving slower and slower. Now use Javascript to simulate these two effects. The principle is to use setInterval or setTimeout to dynamically change the distance between one element and another element, such as xxx.style.left or xxx.style.marginLeft, and then increase the speed after each exercise, so that the effect of accelerating the movement appears. The same is true for decelerating the movement.
Here are two examples:
Accelerate movement
The code copy is as follows:
<!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">GO</button>
<div id="div1"></div>
</body>
</html>
Note: In this example, after clicking GO, the div block will continue to accelerate to the right.
Reduce exercise
The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Reduction Movement</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">GO</button>
<div id="div1"></div>
</body>
</html>
Note: In this example, after clicking GO, the div block will continue to decelerate to the right until the speed decreases to zero, the speed becomes negative, and then accelerate to the left.