<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>拖拽组件的开发</title> <style> div { width: 100px; height: 100px; background: #ccc; position: absolute; } </style> </head> <body> <div id="div1"></div> <div id="div2"></div> </body> <script> (function (global){ function extend(obj1,obj2){ for(var attr in obj2){ obj1[attr] = obj2[attr]; } } "use strict"; var Drag = function (id){ this.obj = document.getElementById(id); this.defaultX = 0; this.defaultY = 0; }; Drag.prototype = { init : function (defaultX,defaultY){ defaultX? this.defaultX = defaultX: this.defaultX = 0; defaultY? this.defaultY = defaultY: this.defaultY = 0; this.obj.style.left = defaultX + 'px'; this.obj.style.top = defaultY + 'px'; var _this = this; this.obj.onmousedown = function (ev){ var ev = ev || window.event; _this.fnDown(ev); document.onmousemove = function (ev){ var ev = ev || window.event; _this.fnMove(ev); } return false; } this.obj.onmouseup = function (){ _this.fnUp(); } }, fnDown : function (ev){ this.defaultX = ev.clientX - this.obj.offsetLeft; this.defaultY = ev.clientY - this.obj.offsetTop; }, fnMove:function (ev){ this.obj.style.left = ev.clientX - this.defaultX + 'px'; this.obj.style.top = ev.clientY - this.defaultY + 'px'; }, fnUp : function (){ document.onmousedown = null; document.onmousemove = null; } }; var DragChild = function (id){ Drag.call(this,id); } extend(DragChild.prototype,Drag.prototype); DragChild.prototype.fnMove = function (ev){ var L = ev.clientX - this.defaultX; var T = ev.clientY - this.defaultY; L < 0 ? L = 0 : L; L > document.documentElement.clientWidth-this.obj.offsetWidth ? L = document.documentElement.clientWidth-this.obj.offsetWidth : L; T < 0 ? T = 0 : T; T > document.documentElement.clientHeight-this.obj.offsetHeight ? T = document.documentElement.clientHeight-this.obj.offsetHeight : T; this.obj.style.left = L + 'px'; this.obj.style.top = T + 'px'; } global.Drag = Drag; global.DragChild = DragChild; })(this); var myDrag1 = new Drag('div1'); myDrag1.init(100,200); var myDrag2 = new DragChild('div2'); myDrag2.init(); </script> </html>