继续改写在浏览器中移动的div,使用面向对象。
这是一步一步在进阶,想了解过程请看我前两篇博客。
https://www.cnblogs.com/duanhuarong/p/12195466.html
https://www.cnblogs.com/duanhuarong/p/12195575.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * {margin: 0;padding: 0;} #div1 { 200px;height: 200px;position: absolute;left: 0;background: red;} </style> </head> <body> <div id="div1"></div> <script> let Odiv = document.getElementById("div1"); function Breakout(Odiv) { //对象 构造函数 this.Odiv = Odiv; this.x = 0; this.y = 0; } Breakout.prototype = { //原型方法 init() { //初始化系统 this.divStar(); //初始化div }, divStar() { this.Odiv.style.top = this.y + 'px'; this.Odiv.style.left = this.x + 'px'; this.disX = 5; this.disY = 5; this.maxWidth = window.innerWidth - this.Odiv.offsetWidth - this.disX; this.maxHeight = window.innerHeight - this.Odiv.offsetHeight - this.disY; let that = this; window.onload = function () { that.ballMove(); } }, ballMove() { //div开始运动 function auto() { if (this.x >= this.maxWidth) this.disX *= -1; if (this.y >= this.maxHeight) this.disY *= -1; if (this.x < 0) this.disX *= -1; if (this.y < 0) this.disY *= -1; this.x += this.disX; this.y += this.disY; this.Odiv.style.left = this.x + 'px'; this.Odiv.style.top = this.y + 'px'; window.requestAnimationFrame(auto.bind(this)); } auto.call(this); }, } var breakout = new Breakout(Odiv); breakout.init(); </script> </body> </html>