研究了两天的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
Title DragLimitDrag