ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
#编写继承的拖拽 ``` <style> #div1, #div2 { width: 100px; height: 100px; position: absolute; } #div1 { background: #c40000; } #div2 { background: green; left: 100px; } </style> <script> window.onload = function () { var d1 = new Drag('div1'); d1.init(); var d2 = new ChildDrag('div2'); d2.init(); }; // 父类拖拽没有限制范围 function Drag(id) { this.obj = document.getElementById(id); this.disX = 0; this.disY = 0; } Drag.prototype.init = function () { var _this = this; this.obj.onmousedown = function (e) { var e = e || window.event; _this.fnDown(e); document.onmousemove = function (e) { var e = e || window.event; _this.fnMove(e); }; document.onmouseup = function () { _this.fnUp(); }; return false; }; }; Drag.prototype.fnDown = function (e) { this.disX = e.clientX - this.obj.offsetLeft; this.disY = e.clientY - this.obj.offsetTop; }; Drag.prototype.fnMove = function (e) { this.obj.style.left = e.clientX - this.disX + 'px'; this.obj.style.top = e.clientY - this.disY + 'px'; }; Drag.prototype.fnUp = function () { document.onmousemove = null; document.onmouseup = null; }; // 子类拖拽有限制范围 function ChildDrag(id) { Drag.call(this, id); } extend(ChildDrag.prototype, Drag.prototype); ChildDrag.prototype.fnMove = function (e) { var L = e.clientX - this.disX; var T = e.clientY - this.disY; if(L < 0){ L = 0; }else if(L > document.documentElement.clientWidth - this.obj.offsetWidth){ L = document.documentElement.clientWidth - this.obj.offsetWidth; } if(T < 0){ T = 0; }else if(T > document.documentElement.clientHeight - this.obj.offsetHeight){ T = document.documentElement.clientHeight - this.obj.offsetHeight; } this.obj.style.left = L + 'px'; this.obj.style.top = T + 'px'; }; function extend(obj1, obj2) { for (var attr in obj2) { obj1[attr] = obj2[attr]; } } </script> <div id="div1"></div> <div id="div2"></div> ```