<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> </title>
</head>
<body>
<div id="div" style="border: 1px solid; width: 80px; height: 50px; background-color:#CF0; text-align: center">
</div>
<div id="black" style="border: 1px solid; width: 40px; height: 40px; background-color:#333"> </div>
<script type="text/javascript">
EventUtil = {
on: function(el, type, listener) {
if (el.addEventListener) {
el.addEventListener(type, listener, false);
} else if (el.attachEvent) {
el.attachEvent('on' + type, listener)
} else {
el['on' + type] = listener;
}
},
un: function(el, type, listener) {
if (el.removeEventListener) {
el.removeEventListener(type, listener);
} else if (el.detachEvent) {
el.detachEvent('on' + type, listener);
} else {
el['on' + type] = null;
}
}
}
DragWraper = function(dom, config) {
this.el = this.getEl(dom);
this.initDrag();
}
DragWraper.prototype = (function() {
var $ = function(id) {
return document.getElementById(id);
}
return {
getEl: function(id) {
if (typeof id == 'string') {
return $(id);
} else {
return id;
}
},
initDrag: function() {
var me = this;
var start = function(e) {
me.state = 'dragStart';
me.el.style.cursor = 'pointer';
me.offsetX = e.clientX - me.el.offsetLeft;
me.offsetY = e.clientY - me.el.offsetTop;
};
var move = function(e) {
if(me.state == 'dragStart') {
me.el.style.left = e.clientX - me.offsetX + 'px';
me.el.style.top = e.clientY - me.offsetY + 'px';
}
}
var stop = function(e) {
me.state = 'end';
};
if (this.el != null) {
this.el.style.position= 'absolute';
EventUtil.on(this.el, 'mousedown', start);
EventUtil.on(this.el, 'mousemove', move)
EventUtil.on(this.el, 'mouseup', stop);
EventUtil.on(this.el, 'mouseout', stop);
}
}
}
})();
new DragWraper('div');
</script>
</body>
</html>