原生 JS 实现一个 DIV 的碰撞反弹运动:
关键在于 DIV 的边界检测, 进而改变运动方向, 即可实现碰撞反弹效果.
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- Title
- </title>
- <style>
- *{margin:0;} div{height:100px;width:100px;background:red;position:absolute;}
- /* 添加绝对定位 */
- </style>
- <script>
- Windows.onload = function() {
- var btn = document.getElementById("btn");
- var div = document.getElementById("div");
- var speedx = 6; // 前端全栈学习交流圈: 866109386
- var speedy = 8; // 面向 1-3 年前端开发人员
- var t = null; // 帮助突破技术瓶颈, 提升思维能力, 欢迎大家.
- btn.onclick = function() {
- clearInterval(t);
- t = setInterval(function() {
- var l = div.offsetLeft + speedx;
- var t = div.offsetTop + speedy;
- if (l >= document.documentElement.clientWidth - div.offsetWidth) {
- speedx *= -1;
- l = document.documentElement.clientWidth - div.offsetWidth;
- } else if (l <= 0) {
- speedx *= -1;
- l = 0;
- }
- if (t >= document.documentElement.clientHeight - div.offsetHeight) {
- speedy *= -1;
- t = document.documentElement.clientHeight - div.offsetHeight;
- } else if (t <= 0) {
- speedy *= -1;
- t = 0;
- }
- div.style.left = l + "px";
- div.style.top = t + "px";
- },
- 10);
- }
- }
- </script>
- </head>
- <body>
- <input type="button" id="btn" value="开始运动">
- <div id="div">
- </div>
- </body>
- </HTML>
来源: http://www.qdfuns.com/article/51070/3141db13a941112ea5a701262c79b10b.html