💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
### 使用继承 - 限制范围的拖拽类 - 构造函数的伪装 - 属性的继承 - 原理 - `call` 的使用 ```js function A() { this.abc = 12; } A.rototype.show = { alert(this.abc); } function B() { A.call(this); // 用 call 继承属性,把B传入A函数内 } // B.prototype = A.prototype; // 浅复制方法是引用,指向同一个内存空间 for (var i in A.prototype) { B.prototype[i] = A.ptoyotype[i]; // 深度复制就不会引用,直接复制内容 } var obj = new B(); alert(obj.abc); obj.show.call(); // call 一般省略 ``` - 原型链 - 方法的继承 - 原理:**复制方法是引用,指向同一个内存空间** - 覆盖原型的方法复制 - `for in` 深度复制就不会引用,直接复制内容 - 代码:拖拽改写为面对对象并继承一个新的对象 ```HTML <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>面对对象的拖拽</title> <link rel="stylesheet" href="../reset.css"> <style> #div1 { top: 100px; left: 100px; width: 200px; height: 200px; position: absolute; background-color: rgb(255, 0, 0); } #div2 { width: 200px; height: 200px; position: absolute; background-color: rgb(0, 255, 170) } </style> <script src="./lib/Drag.js"></script> <script src="./lib/LimitDrag.js"></script> <script> window.onload = function () { new Drag('div1'); new LimitDrag('div2'); } </script> </head> <body> <div id="div1">普通拖拽</div> <div id="div2">限制范围的拖拽</div> </body> </html> ``` ```JS function Drag(id) { this.disX = ''; this.disY = ''; this.oDiv = document.getElementById(id); var _this = this; this.oDiv.onmousedown = function (ev) { _this.fnDown(ev); return false; }; } Drag.prototype.fnDown = function (ev) { var ev = event||ev; var _this = this; // 鼠标可视区位置 - div左边距 = 鼠标在div内的位置 this.disX = ev.clientX - this.oDiv.offsetLeft; this.disY = ev.clientY - this.oDiv.offsetTop; console.log(this.disX,'可视区鼠标X:', ev.clientX, '鼠标Y:',ev.clientY); document.onmousemove = function (ev) { _this.mouseMove(ev); } document.onmouseup = function (ev) { _this.mouseUp(ev); } } Drag.prototype.mouseMove = function(ev) { // 不断获取Event 对象,坐标才会不断更新 var ev = event||ev; // console.log('可视区鼠标X:', ev.clientX, '鼠标Y:',ev.clientY); // div位置 = 鼠标可视区新的位置 - 鼠标与div的距离 this.oDiv.style.left = ev.clientX - this.disX + 'px'; this.oDiv.style.top = ev.clientY - this.disY + 'px'; } Drag.prototype.mouseUp = function () { document.onmousemove = ''; document.onmouseup = ''; } ``` ```JS // 继承属性 function LimitDrag(id) { Drag.call(this, id); } // 继承原型 for (var i in Drag.prototype) { LimitDrag.prototype[i] = Drag.prototype[i]; } LimitDrag.prototype.mouseMove = function(ev) { // 不断获取Event 对象,坐标才会不断更新 var ev = event||ev; // console.log('可视区鼠标X:', ev.clientX, '鼠标Y:',ev.clientY); // div位置 = 鼠标可视区新的位置 - 鼠标与div的距离 var l = ev.clientX - this.disX; var t = ev.clientY - this.disY; if (l < 0) { l = 0; } else if (l > document.documentElement.clientWidth - this.oDiv.offsetWidth) { l = document.documentElement.clientWidth - this.oDiv.offsetWidth; } if ( t < 0) { t = 0; } else if (t > document.documentElement.clientHeight - this.oDiv.offsetHeight) { t = document.documentElement.clientHeight - this.oDiv.offsetHeight; } this.oDiv.style.top = t + 'px'; this.oDiv.style.left = l + 'px'; } ```