<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* 为两个div添加样式 */ #box1{ 100px;height: 100px;background: red;position: absolute;left: 0;top: 0;} #box2{ 100px;height: 100px;background: blue;position: absolute;left: 0;top: 150px;} </style> </head> <body> <!-- 创建两个div标签 --> <div id="box1"></div> <div id="box2"></div> </body> <script> //1.创建构造函数: function Drag(ele){ this.ele = ele; //提前将,未来的事件处理函数中的this指向修复,得到修复之后的新函数,用来绑定或删除使用 this.m = this.move.bind(this); this.u = this.up.bind(this); this.addEvent(); } //给元素绑定鼠标事件: Drag.prototype.addEvent = function(){ var that = this; this.ele.addEventListener("mousedown",function(eve){ that.downE = eve || window.event; document.addEventListener("mousemove",that.m); document.addEventListener("mouseup",that.u); }) } //鼠标移动事件: Drag.prototype.move = function(eve){ let moveE = eve || window.event; this.ele.style.left = moveE.clientX - this.downE.offsetX + "px"; this.ele.style.top = moveE.clientY - this.downE.offsetY + "px"; } //鼠标抬起事件: Drag.prototype.up = function(){ document.removeEventListener("mousemove",this.m); document.removeEventListener("mouseup",this.u) } //创建构造函数: function SmallDrag(ele){ Drag.call(this,ele); } SmallDrag.prototype = Object.create(Drag.prototype); SmallDrag.prototype.move = function(eve){ var moveE = eve || event; var l = moveE.clientX - this.downE.offsetX; var t = moveE.clientY - this.downE.offsetY; if(l<0) l=0; if(t<0) t =0; if(l>(document.documentElement.clientWidth- this.ele.offsetWidth)) l = document.documentElement.clientWidth- this.ele.offsetWidth; if(t>(document.documentElement.clientHeight- this.ele.offsetHeight)) t = document.documentElement.clientHeight- this.ele.offsetHeight this.ele.style.left = l + "px"; this.ele.style.top = t + "px"; } //获取标签: var obox1 = document.getElementById("box1"); var obox2 = document.getElementById("box2"); new Drag(obox1) new SmallDrag(obox2) </script> </html>