js实现盒子移动动画效果

时间:2022-12-05 18:25:47

本文实例为大家分享了js实现盒子移动动画效果的具体代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta name="viewport"
   content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 <meta http-equiv="x-ua-compatible" content="ie=edge">
 <title>document</title>
 <style>
  .box {
   width: 200px;
   height: 200px;
   border: 1px solid red;
   position: absolute;
   left: 0;
   top: 50px;
  }
 </style>
</head>
<body>
<input type="button" value="前进" id="box_start">
<input type="button" value="停止" id="box_stop">
<input type="button" value="回退" id="box_back">
<br><br>
<div id="box" class="box">
 
</div>
<script>
 let boxstart = document.getelementbyid("box_start");
 let boxstop = document.getelementbyid("box_stop");
 let boxback = document.getelementbyid("box_back");
 let timeid_1;
 let timeid_2;
 
 boxstart.onclick = function () {
  let box = document.getelementbyid("box");
  clearinterval(timeid_2);
  timeid_1 = setinterval(function () {
   if (box.offsetleft >= 600) {
    clearinterval(timeid_1);
    box.style.left = 600 + 'px';
    alert('到达目的地');
   } else {
    box.style.left = box.offsetleft + 10 + 'px';
   }
  }, 100);
 };
 boxback.onclick = function () {
  let box = document.getelementbyid("box");
  clearinterval(timeid_1);
  timeid_2 = setinterval(function () {
   if (box.offsetleft <= 0) {
    clearinterval(timeid_2);
    box.style.left = "0";
    alert('已在出发位置');
   } else {
    box.style.left = box.offsetleft - 10 + 'px';
   }
  }, 100);
 };
 boxstop.onclick = function () {
  clearinterval(timeid_1);
  clearinterval(timeid_2);
 };
</script>
</body>
</html>

效果图:

js实现盒子移动动画效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/cnkeysky/article/details/86761612