1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title></title>
6 <style type="text/css">
7 *{
8 padding: 0;
9 margin: 0;
10 }
11 #box{
12 width: 500px;
13 height: 400px;
14 border: 1px solid gainsboro;
15 margin: 20px auto 0;
16 position: relative;
17 }
18 #ball{
19 width: 30px;
20 height: 30px;
21 border-radius: 50%;
22 background: red;
23 position: absolute;
24 }
25 </style>
26 </head>
27 <body>
28 <div id="box">
29 <div id="ball"></div>
30 </div>
31 </body>
32 <script type="text/javascript">
33 // 获取 box 和 ball
34 var box = document.getElementById("box");
35 var ball = document.getElementById("ball");
36 // 获取小球可以移动的最大高度
37 var maxHeight = box.clientHeight - ball.offsetHeight;
38 // 获取小球可以移动的最大宽度
39 var maxWidth = box.clientWidth - ball.offsetWidth;
40
41 // 获取小球的初始 top 值
42 var originTop = ball.offsetTop;
43 // 获取小球的初始 left 值
44 var originLeft = ball.offsetLeft;
45
46 //定义一个变量用来记录x 轴方向移动的宽度
47 var speedX = 0;
48
49 var x_select = true;
50 setInterval(function(){
51 if(speedX <= 0){
52 x_select = true
53 }else if(speedX >= maxWidth){
54 x_select = false;
55 }
56
57 if(x_select == true){
58 speedX += 5;
59 }else{
60 speedX -= 5;
61 }
62
63
64 ball.style.left = originLeft + speedX + "px";
65
66 },30);
67
68
69
70 </script>
71 </html>