(function(win, doc){
var _this = null;
var info = {};
var list = [];
var Sortable = function(opts) {
this.opts = opts;
_this = this;
list = X.getByClass(this.opts.sortClass, doc);
X.addEvent(doc, 'mousedown', this.handleEvent);
X.addEvent(doc, 'mousemove', this.handleEvent);
X.addEvent(doc, 'mouseup', this.handleEvent);
};
Sortable.prototype = {
handleEvent: function(event) {
var e = event || win.event;
var target = event.target || event.srcElement;
switch (event.type) {
case 'mousedown':
X.hasClass(target, _this.opts.sortClass) && _this.downEvent.call(_this, e, target);
break;
case 'mousemove':
info.dObj && _this.moveEvent.call(_this, e, target);
break;
case 'mouseup':
info.dObj && _this.upEvent.call(_this, e, target);
break;
default: break;
}
},
downEvent: function(e, target) {
info.dObj = target;
var off = X.getOffset(target);
target.x = e.clientX - off[0];
target.y = e.clientY - off[1];
target.style.position = 'absolute';
target.style.left = off[0] +'px';
target.style.top = off[1] +'px';
info.vObj = doc.createElement('div');
info.vObj.style.width = off[2] +'px';
info.vObj.style.height = off[3] +'px';
target.parentNode.insertBefore(info.vObj, target);
},
moveEvent: function(e, target) {
win.getSelection ? win.getSelection().removeAllRanges() : doc.selection.empty();
info.dObj.style.left = e.clientX - info.dObj.x +'px';
info.dObj.style.top = e.clientY - info.dObj.y +'px';
for(var i = 0; i < list.length; i++) {
if(list[i] === info.dObj) {
continue;
}
var off = X.getOffset(list[i]);
if(e.clientX > off[0] && e.clientX < off[0] + off[2] && e.clientY > off[1] && e.clientY < off[1] + off[3]) {
switch (true) {
case e.clientY < (off[1] + off[3]) / 2:
list[i].parentNode.insertBefore(info.vObj, list[i]);
break;
case !list[i].nextSibling:
list[i].parentNode.appendChild(info.vObj);
break;
default:
list[i].parentNode.insertBefore(info.vObj, list[i].nextSibling);
break;
}
}
}
},
upEvent: function(e, target) {
info.dObj.style.position = 'static';
info.vObj.parentNode.insertBefore(info.dObj, info.vObj);
info.dObj.parentNode.removeChild(info.vObj);
info = {};
}
};
win.Sortable = Sortable;
})(window, document);
您可能感兴趣的文章: