分享一个通过面向对象方式完成的拖拽功能
研究了两天的JS面向对象了,然后根据视频完成了一个简单的拖拽功能。下面的代码其实很简单,唯一需要注意的就是 this ,感觉JS中的this还是很奇妙很有意思的,接下来学习就研究this指针好啦 。
下面是拖拽的代码
Drag.js
function Drag(id){ var _this = this; this.divX = 0; this.divY = 0; this.oDiv = document.getElementById(id); this.oDiv.onmousedown = function(ev){ _this.fnMouseDown(ev); } } Drag.prototype.fnMouseDown = function(ev){ var _this = this; var oEvent = ev||event; this.divX = oEvent.clientX - this.oDiv.offsetLeft; this.divY = oEvent.clientY - this.oDiv.offsetTop; document.onmousemove = function(ev){ _this.fnMouseMove(ev); return false;//取消选中 }; document.onmouseup = function(){ _this.fnMouseUp(); } } Drag.prototype.fnMouseMove = function(ev){ var oEvent = ev||event; this.oDiv.style.left = oEvent.clientX - this.divX+'px'; this.oDiv.style.top = oEvent.clientY- this.divY+'px'; } Drag.prototype.fnMouseUp = function(){ document.onmousemove = null; document.onmousedown = null; }
LimitDrag.js //限制范围的拖拽
/** * Created by Administrator on 2015/12/29 0029. */ function LimitDrag (id){ Drag.call(this,id); } for(var i in Drag.prototype){ LimitDrag.prototype[i] = Drag.prototype[i]; } //重写 MouseMove 函数 LimitDrag.prototype.fnMouseMove = function(ev){ var oEvent = ev||event; var left = oEvent.clientX - this.divX; var top = oEvent.clientY - this.divY if(left<0){ left = 0; }else if(left >document.documentElement.clientWidth - this.oDiv.offsetWidth){ left= document.documentElement.clientWidth - this.oDiv.offsetWidth; } if(top<0){ top = 0; }else if(top > document.documentElement.clientHeight - this.oDiv.offsetHeight){ top = document.documentElement.clientHeight - this.oDiv.offsetHeight } this.oDiv.style.left = left+'px'; this.oDiv.style.top = top+'px'; }
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/Drag.js"></script> <script src="js/LimitDrag.js"></script> <script> window.onload = function () { new Drag('div1'); new LimitDrag('div2') } </script> <style> #div1{ width: 200px; height: 200px; background-color: yellow; position: absolute; } #div2{ width: 200px; height: 200px; background-color: blue; position: absolute; } </style> </head> <body> <div id="div1">Drag</div> <div id="div2">LimitDrag</div> </body> </html>