总结:
1、position: relative;相对位置进行移动;
2、用setInterval() 方法设置定时器,会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭;
3、 ball.style.left = ball.style.top = count + 'px'; 来设置向左和上进行移动;
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <style> div{ border: 2px solid #000; height: 40px; width: 40px; border-radius: 40px; margin: 50px 10px; background-color: #000; box-shadow: 2px 2px 2px #000; position: relative; } </style> <body> <button type="button" onclick="myBall()">点击</button> <div id="ball"></div> <script> function myBall() { var ball = document.getElementById("ball"); var count = 0; var id = setInterval(frame, 10); function frame() { if (count < 100) { cont++; ball.style.left = ball.style.top = count + 'px'; } else { clearInterval(id); } } } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例