原生js拖拽

  好吧,js拖拽这个很多笔试面试都考过了,so,写一个练练手吧!

function Drag(obj) {
this.obj = obj;
}
Drag.prototype = {
constructor : Drag,
getInitPosition : function(e) {
e = e || window.event;
var eX, eY;
if (e.pageX || e.pageY) {
eX = e.pageX;
eY = e.pageY;
}
eX = e.clientX;
eY = e.clientY;
var positionX = eX - this.obj.offsetLeft;
var positionY = eY - this.obj.offsetTop;
return {
x : positionX,
y : positionY
}
},
getmouseCoordinate : function(e) {
e = e || window.event;
if (e.pageX || e.pageY) {
return {
x : e.pageX,
y : e.pageY
};
}
return {
x : e.clientX + document.body.scrollLeft - document.body.clientLeft,
y : e.clientY + document.body.scrollTop - document.body.clientTop
};
},
initDrag : function() {
var tempThis = this;
this.obj.onmousedown = function(e) {
var initP = tempThis.getInitPosition();
document.onmousemove = function(e) {
var moveP = tempThis.getmouseCoordinate();
tempThis.obj.style.marginTop = moveP.y - initP.y + "px";
tempThis.obj.style.marginLeft = moveP.x - initP.x + "px";
}
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
}
}
}
var drag = document.getElementById("drag1");
var dragElement = new Drag(drag);
dragElement.initDrag();

  

posted @ 2015-03-25 14:13  低调的大白兔  阅读(167)  评论(0编辑  收藏  举报